答案 0 :(得分:1)
您可以尝试将条件恶化功能与UNION ALL
一起使用
SELECT TYear,
TMonth,
'D1' Day,
MAX(CASE WHEN USER = 'Sam' THEN D1 END) Sam,
MAX(CASE WHEN USER = 'Rahul' THEN D1 END) Rahul
FROM tblCallAttend
GROUP BY TYear,
TMonth
UNION ALL
SELECT TYear,
TMonth,
'D2' Day,
MAX(CASE WHEN USER = 'Sam' THEN D2 END) Sam,
MAX(CASE WHEN USER = 'Rahul' THEN D2 END) Rahul
FROM tblCallAttend
GROUP BY TYear,
TMonth
SELECT TYear,
TMonth,
'D3' Day,
MAX(CASE WHEN USER = 'Sam' THEN D3 END) Sam,
MAX(CASE WHEN USER = 'Rahul' THEN D3 END) Rahul
FROM tblCallAttend
GROUP BY TYear,
TMonth
.....
答案 1 :(得分:1)
样本数据
;WITH CTE(Tyear,Tmonth,[User],d1,d2,d3,d4,d5)
AS
(
SELECT 2019,'Jan','Sam',249,297,296,288,269 UNION ALL
SELECT 2019,'Jan','Rahul',300,237,452,142,475
)
SELECT * INTO #Temp FROM CTE
Sql脚本
SELECT [Tyear],Tmonth,Dayz,[Sam],[Rahul]
FROM
(
SELECT o.Tyear,
o.Tmonth ,
Dayz,
dayval,
dt.[User]
FROM #Temp o
CROSS APPLY ( VALUES ('d1',d1,[User]),('d2',d2,[User]),('d3',d3,[User]),('d4',d4,[User]),('d5',d5,[User]))
AS dt (Dayz,dayval,[User])
)AS SRc
PIVOT
(
MAX(dayval) FOR [User] IN ([Sam],[Rahul])
)AS Pvt
结果
Tyear Tmonth Dayz Sam Rahul
----------------------------------
2019 Jan d1 249 300
2019 Jan d2 297 237
2019 Jan d3 296 452
2019 Jan d4 288 142
2019 Jan d5 269 475
答案 2 :(得分:0)
您要取消数据透视。我为此建议使用横向联接,这在SQL Server中意味着apply
关键字:
select ca.tyear, ca.tmonth, v.day,
(case when ca.user = 'Sam' then v.val end) as Sam,
(case when ca.user = 'Rahul' then v.val end) as Rahul
from tblCallAttend ca cross apply
(values ('D1', ca.d1),
('D2', ca.d2),
('D3', ca.d3),
('D4', ca.d4),
('D5', ca.d5)
) v(day, val)
order by ca.tyear, ca.tmonth, v.day;
横向联接非常强大。取消数据透视等问题是了解它们的便捷方法。