我正在尝试在SQLServer中为我的报告构建这种类型的查询,但是对于分支。
Branch_ID Branch_Name
CheckList_ID CheckList_Name
CheckList_ID Branch_ID Chk_Value ResponseDate
现在我想只传递月份和年份,它应该执行以下操作。 注意:我已经从oracle论坛上获取了MONTHS的要求,但我想要分支。另请注意,例如,如果我在详细信息表中有12个分支但在master中仍有28个分支,我需要在查询中显示28个分支,如果没有详细表中的相关分支数据则显示0值。
select
c_name,
sum(decode(mon, 'Jan', pono, 0)) jan,
sum(decode(mon, 'Feb', pono, 0)) feb,
.....
.....
sum(decode(mon, 'Nov', pono, 0)) nov,
sum(decode(mon, 'Dec', pono, 0)) dec,
sum(decode(mon, 'Mon_Total', pono, 0)) mtotal
from (
select decode(grouping(c_name), 1, 'Total', c_name) c_name,
decode(grouping(month), 0, month, 'Mon_Total') mon, sum(po_no) pono
from t
group by cube(c_name, month)
)
group by c_name
And the result may look like:
C_NAME BR1 BR2 BR3 BR4 BR5 BR6 BR7 BR8 BR9 BR10 BR11 BR12 TOTAL_OF_ROW
------------------------------ ---------- ---------- ---------- ----------
---------- ---------- ---------- ---------- ---------- ---------- ----------
CHKLST1 1 2 3 4 5 6 7 8 9 10 11 12 78
CHKLST2 20 30 40 50 60 70 80 90 100 110 120 780
答案 0 :(得分:0)
使用PIVOT。
SELECT *
FROM
(
SELECT c.CheckList_Name,
b.BranchName,
COUNT(*) ItemCount
FROM dbo.CheckList_Detail cd
JOIN dbo.CheckList_Master c
ON c.CheckList_ID = cd.CheckList_ID
JOIN dbo.Branch_Master b
ON b.Branch_ID = cd.Branch_ID
) a
PIVOT
(
MIN(ItemCount) FOR BranchName IN
(
[BR1], [BR2], [BR3], [BR4], [BR5], [BR6],
[BR7], [BR8], [BR9], [BR10], [BR11], [BR12]
)
) b