如何连接下面两个分组的查询?
select [Fiscal Year],[Fiscal Quater],sum([colX])as X
from table1
group by [Fiscal Year],[Fiscal Quater];
select [Fiscal Year],[Fiscal Quater],sum([colY]) as Y
from table2
group by [Fiscal Year],[Fiscal Quater];
结果应该返回列: [财政年度],[财政部],X,Y
答案 0 :(得分:1)
你可能想要这样的东西:
select coalesce(t1.[Fiscal Year], t2.[Fiscal Year]) as [Fiscal Year],
coalesce(t1.[Fiscal Quater], t2.[Fiscal Quater]) as [Fiscal Quater],
coalesce(t1.X, 0) as X,
coalesce(t2.Y, 0) as Y
from (
select [Fiscal Year], [Fiscal Quater], sum([colX]) as X
from table1
group by [Fiscal Year], [Fiscal Quater]) as t1
full join (
select [Fiscal Year], [Fiscal Quater], sum([colY]) as Y
from table2
group by [Fiscal Year], [Fiscal Quater]
) as t2 on t1.[Fiscal Year] = t2.[Fiscal Year] and
t1.[Fiscal Quater] = t2.[Fiscal Quater]
答案 1 :(得分:0)
UNION ALL
在派生表中将两个表放在一起,在主级别执行GROUP BY
:
select [Fiscal Year], [Fiscal Quater], sum([colX])as X, sum([colY]) as Y
from
(
select [Fiscal Year], [Fiscal Quater], colX, NULL as colY from table1
UNION ALL
select [Fiscal Year], [Fiscal Quater], NULL as colX, colY from table2
)
group by [Fiscal Year],[Fiscal Quater]
或者,请加倍GROUP BY
:
select [Fiscal Year], [Fiscal Quater], sum(X), sum(Y)
from
(
select [Fiscal Year], [Fiscal Quater], sum([colX]) as X, NULL as Y
from table1
group by [Fiscal Year],[Fiscal Quater];
UNION ALL
select [Fiscal Year], [Fiscal Quater], NULL as X, sum([colY]) as Y
from table2
group by [Fiscal Year],[Fiscal Quater]
)
group by [Fiscal Year],[Fiscal Quater]
也许以不同方式进行优化?
答案 2 :(得分:0)
您可以使用以下CTE:
WITH T1 AS
(
SELECT [Fiscal year], [Fiscal quater], Value = colX FROM table1
),
T2 AS
(
SELECT [Fiscal year], [Fiscal quater], Value = colY FROM table2
)
SELECT [T1.Fiscal Year],[T1.Fiscal Quater],
X = SUM(T1.Value),
Y = SUM(T2.Value)
FROM T1 FULL OUTER JOIN T2
ON T1.[Fiscal year] = T2.[Fiscal year]
AND T1.[Fiscal quater] = T2.[Fiscal quater]
GROUP BY [T1.Fiscal Year], T1.[Fiscal quater]