Sql-Server

返回第一個非零值

  • September 1, 2017

我想要的結果集是

Red  Purple
1     5

都在一排

我下面的查詢返回 4 行。

只返回 1 行的語法是什麼?

DECLARE @BlueBonnet TABLE (
   randarfield FLOAT
   ,confis VARCHAR(10)
   );

INSERT INTO @BlueBonnet (randarfield, confis)
VALUES('0.00', 'red'), ('0.00','red'), ('0.00','blue'), ('0.00','blue')
   , ('0.00','purple'), ('5.00','purple'), ('0.00','orange')
   , ('1.00','red'), ('0.00','blue'), ('0.00','blue')

SELECT Red  = CASE WHEN confis = 'red' THEN MAX(randarfield) ELSE 0 END
   ,Purple = CASE WHEN confis = 'purple' THEN MAX(randarfield) ELSE 0 END
FROM @BlueBonnet
GROUP BY confis

這裡有兩個選項:

根據您的**MAX**:

SELECT
    MAX(CASE WHEN confis = 'red'    THEN randarfield END) AS Red
   ,MAX(CASE WHEN confis = 'purple' THEN randarfield END) AS Purple
FROM @BlueBonnet

但如果你真的想要第一個(不是最大值):

SELECT
(SELECT TOP 1 randarfield FROM @BlueBonnet WHERE randarfield>0 AND confis = 'red'   ) Red
,(SELECT TOP 1 randarfield FROM @BlueBonnet WHERE randarfield>0 AND confis = 'purple') Purple

儘管根據您對“第一”的定義,您需要為ORDER BY ...您訂購的任何列添加兩個子查詢來決定什麼是第一。

引用自:https://dba.stackexchange.com/questions/184858