具有多个字段的 SSMS Case 语句
SSMS Case Statement With Multiple Fields
我有一个用于求和、舍入和标记金额的 case 语句,效果很好,但数据最终以水平格式结束(每条记录有多个金额),导致我在后续语句中进行逆透视以格式化垂直数据(每条记录一个金额)。如果可能的话,我想在一个声明中完成这个。我的代码如下:
SELECT
Field,
ROUND(SUM(CASE
WHEN TYPE = 'Paid Loss'
THEN AMOUNT
ELSE 0
END
), 2
) PAID,
ROUND(SUM(CASE
WHEN TYPE = 'OS'
THEN AMOUNT
ELSE 0
END
), 2
) OS,
ROUND(SUM(CASE
WHEN TYPE <> 'Paid Exp'
THEN AMOUNT
ELSE 0
END
), 2
) INCURRED
FROM dbo.mydatabase
GROUP BY Field;
结果是:
Field |PAID |OS |INCURRED
----------------------------
result1 | 1 | 20 | 10
result2 | 5 | 30 | 15
当我真正想要的是:
Field | DATA_TYPE | AMOUNT
---------------------------
result1 | PAID | 1
result2 | PAID | 5
result3 | OS | 20
result4 | OS | 30
result5 | INCURRED | 10
result6 | INCURRED | 15
密钥将是唯一的,所以这不是问题。任何人都知道如何重新排列 CASE 以便可以在一条语句中完成?谢谢!
这不行吗?
SELECT Field, 'PAID' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE = 'Paid Loss'
GROUP BY Field
UNION ALL
SELECT Field, 'OS' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE = 'OS'
GROUP BY Field
UNION ALL
SELECT Field, 'INCURRED' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE <> 'Paid Exp'
GROUP BY Field
甚至像这样:
SELECT Field
, (CASE
WHEN TYPE IN ('Paid Loss', 'OS') THEN TYPE
WHEN TYPE <> 'Paid Exp' THEN 'INCURRED'
END) DATA_TYPE
, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
GROUP BY Field
, (CASE
WHEN TYPE IN ('Paid Loss', 'OS') THEN TYPE
WHEN TYPE <> 'Paid Exp' THEN 'INCURRED'
END) DATA_TYPE
我有一个用于求和、舍入和标记金额的 case 语句,效果很好,但数据最终以水平格式结束(每条记录有多个金额),导致我在后续语句中进行逆透视以格式化垂直数据(每条记录一个金额)。如果可能的话,我想在一个声明中完成这个。我的代码如下:
SELECT
Field,
ROUND(SUM(CASE
WHEN TYPE = 'Paid Loss'
THEN AMOUNT
ELSE 0
END
), 2
) PAID,
ROUND(SUM(CASE
WHEN TYPE = 'OS'
THEN AMOUNT
ELSE 0
END
), 2
) OS,
ROUND(SUM(CASE
WHEN TYPE <> 'Paid Exp'
THEN AMOUNT
ELSE 0
END
), 2
) INCURRED
FROM dbo.mydatabase
GROUP BY Field;
结果是:
Field |PAID |OS |INCURRED
----------------------------
result1 | 1 | 20 | 10
result2 | 5 | 30 | 15
当我真正想要的是:
Field | DATA_TYPE | AMOUNT
---------------------------
result1 | PAID | 1
result2 | PAID | 5
result3 | OS | 20
result4 | OS | 30
result5 | INCURRED | 10
result6 | INCURRED | 15
密钥将是唯一的,所以这不是问题。任何人都知道如何重新排列 CASE 以便可以在一条语句中完成?谢谢!
这不行吗?
SELECT Field, 'PAID' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE = 'Paid Loss'
GROUP BY Field
UNION ALL
SELECT Field, 'OS' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE = 'OS'
GROUP BY Field
UNION ALL
SELECT Field, 'INCURRED' DATA_TYPE, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
WHERE TYPE <> 'Paid Exp'
GROUP BY Field
甚至像这样:
SELECT Field
, (CASE
WHEN TYPE IN ('Paid Loss', 'OS') THEN TYPE
WHEN TYPE <> 'Paid Exp' THEN 'INCURRED'
END) DATA_TYPE
, ROUND(SUM(AMOUNT), 2) AMOUNT
FROM dbo.mydatabase
GROUP BY Field
, (CASE
WHEN TYPE IN ('Paid Loss', 'OS') THEN TYPE
WHEN TYPE <> 'Paid Exp' THEN 'INCURRED'
END) DATA_TYPE