这是我在SQL Server中面临的问题,我有一个包含以下行的表:
ID | Parameter | Value
123 | A | 0
123 | B | 1.27
123 | C | 2.13
124 | A | 1.29
...
并希望按ID返回此唯一行:
ID | A_Value | C_Value | BothA&C=0?
123| 0 | 2.13 | NO
我该怎么办?
答案 0 :(得分:1)
您可以使用称为“交叉标签”的技术。
SELECT ID,
MAX(CASE WHEN Parameter = 'A' THEN Value END) AS A_Value,
MAX(CASE WHEN Parameter = 'C' THEN Value END) AS C_Value,
CASE WHEN MAX(CASE WHEN Parameter = 'A' THEN Value END) = 0
AND MAX(CASE WHEN Parameter = 'A' THEN Value END) = 0 THEN 'Yes'
ELSE 'No' END AS [BothA&C=0?]
FROM YourTable
GROUP BY ID;
答案 1 :(得分:0)
这里有两个选项-我倾向于发现选项1比选项2更容易编写,但是对您来说更有意义。您可以here对其进行测试(出于示例目的,我添加了一些ID以及相关的参数和值条目)
SELECT
ID
, [A_Value] = MAX(CASE WHEN Parameter = 'A' THEN Value END)
, [C_Value] = MAX(CASE WHEN Parameter = 'C' THEN Value END)
,[BothA&C=0] = (CASE WHEN max(CASE WHEN Parameter = 'A' THEN CAST(Value AS INT) END) = 0 AND max(CASE WHEN Parameter = 'C' THEN CAST(Value AS INT) END) = 0 THEN 'YES' ELSE 'NO' END )
FROM dbo.yourDataTable
GROUP BY ID
SELECT
ID
, [A_Value] = [A]
, [C_Value] = [C]
, [BothA&C=0] = CASE WHEN CAST([A] AS INT) = 0 AND CAST([C] AS INT) = 0 THEN 'YES' ELSE 'NO' END
FROM
(
SELECT
ID
,Parameter
,Value
FROM yourDataTable
) sourceTable
PIVOT
(
MAX(Value) FOR Parameter IN ([A],[C])
) AS pvt