我试图在SQLServer中为我的报告构建这种类型的查询,但是为分支构建这种查询。
Branch_Master
Branch_ID Branch_Name
CheckList_Master
CheckList_ID CheckList_Name
CheckList_Detail
CheckList_ID Branch_ID Chk_Value ResponseDate
现在我只想通过一个月和一年,它应该做如下的事情。注意:我已经从甲骨文论坛获得了这个查询,需要几个月的时间,但我想要分支机构。还请注意,例如,如果我有12个分支的明细表,但在主表中仍有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发布于 2011-01-07 10:09:49
使用枢轴。
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]
)
) bhttps://stackoverflow.com/questions/4624363
复制相似问题