具有这样的表格:
name ZK04_COUNT ZK05_COUNT ZK04_PRICE ZK05_PRICE
A 15 0 150.00 0
A 0 20 0 223.00
B 11 0 75.00 0
B 0 24 0 250.00
我正在尝试将其转为类似这样的内容:
name ZK04_COUNT ZK05_COUNT ZK04_PRICE ZK05_PRICE
A 15 20 150.00 223.00
B 11 24 75.00 250.00
我的代码如下:
SELECT *
FROM (
SELECT
r.name
,r.AUART
, CASE WHEN r.AUART = 'ZK05' THEN count(r.MATNR) ELSE '' END AS ZK05_COUNT
, CASE WHEN r.AUART = 'ZK04' THEN count(r.MATNR) ELSE '' END AS ZK04_COUNT
, CONVERT(money, sum(CAST(netpr as MONEY)), 1) as ToplamTutar
FROM GARANTI_YP_RAPORU as r
group by r.name ,r.AUART
) as gTablo
PIVOT
(
SUM(ToplamTutar)
FOR gTablo.AUART IN ([ZK05],[ZK04])
)
AS p1
我希望输出在单行中。怎么办?
答案 0 :(得分:4)
这真的不需要PIVOT。
仅按名称将它们分组,然后使用条件聚合即可。
SELECT r.name
, COUNT(CASE WHEN r.AUART = 'ZK04' THEN r.MATNR END) AS ZK04_COUNT
, COUNT(CASE WHEN r.AUART = 'ZK05' THEN r.MATNR END) AS ZK05_COUNT
, CAST(SUM(CASE WHEN r.AUART = 'ZK04' THEN r.netpr ELSE 0 END) AS MONEY) AS ZK04_PRICE
, CAST(SUM(CASE WHEN r.AUART = 'ZK05' THEN r.netpr ELSE 0 END) AS MONEY) AS ZK05_PRICE
FROM GARANTI_YP_RAPORU as r
GROUP BY r.name
ORDER BY r.name