按唯一id在SQL中的子查询上分组
我有一个从临时表中获取结果的查询。它具有从临时表派生的聚合列:按唯一id在SQL中的子查询上分组,sql,sql-server,Sql,Sql Server,我有一个从临时表中获取结果的查询。它具有从临时表派生的聚合列: SELECT DISTINCT SUM(a), SUM(b), c, d, id1 FROM #tmpTable . . . join with many other tables 现在,我想获取查询返回的c&d列和所有其他列的总和。它将按id1分组。它应该看起来像: +-------------------------------------------- ||Sum(A) |Sum(B)|C |
SELECT
DISTINCT
SUM(a),
SUM(b),
c,
d,
id1
FROM
#tmpTable
.
.
.
join with many other tables
现在,我想获取查询返回的c&d列和所有其他列的总和。它将按id1分组。它应该看起来像:
+--------------------------------------------
||Sum(A) |Sum(B)|C |D |id1 |
|-------------------------------------------+
| 12 |34 |1 | 3 | 1 |
|-------------------------------------------+
| 22 |37 | 2 | 4 | 2 |
|-------------------------------------------+
| 33 | 55 | 3 | 5 | 1 |
|-------------------------------------------+
| 44 | 25 | 5 | 6 | 2 |
+---------+------+------+---------+---------+
最终结果应该是:
+--------------------------------------------
||Sum(A) |Sum(B)|Sum(C)|Sum(d) |id1 |
|-------------------------------------------+
| 12 |34 |4 | 8 | 1 |
|-------------------------------------------+
| 22 |37 | 7 | 10 | 2 |
|-------------------------------------------+
| 33 | 55 | 4 | 8 | 1 |
|-------------------------------------------+
| 44 | 25 | 7 | 10 | 2 |
+---------+------+------+---------+---------+
鉴于A和B的分组标准不同,您可以将它们分别分组为C和D。下面使用公共表表达式可能会让您走上正确的道路: ; 将总和值作为 选择id1、sumC作为sumC、SUMD作为SUMD 从SourceTable 按id1分组 选择SUMst.A、SUMst.b、sv.SumC、sv.SumD、st.id1 从SourceTable st 内部联接汇总值sv 在st.id1=sv.id1上 分组
鉴于A和B的分组标准不同,您可以将它们分别分组为C和D。下面使用公共表表达式可能会让您走上正确的道路: ; 将总和值作为 选择id1、sumC作为sumC、SUMD作为SUMD 从SourceTable 按id1分组 选择SUMst.A、SUMst.b、sv.SumC、sv.SumD、st.id1 从SourceTable st 内部联接汇总值sv 在st.id1=sv.id1上 分组
如果您当前的实际查询以您想要的方式求和a和b,并生成第一个示例输出,可能类似于:
SELECT DISTINCT
SUM(a),
SUM(b),
SUM(c) OVER (PARTITION BY id1),
SUM(d) OVER (PARTITION BY id1),
id1
FROM
#tmpTable
.
.
.
join with many other tables
获取第二个示例。如果您当前的实际查询以您想要的方式对a和b求和,并生成第一个示例输出,可能类似于:
SELECT DISTINCT
SUM(a),
SUM(b),
SUM(c) OVER (PARTITION BY id1),
SUM(d) OVER (PARTITION BY id1),
id1
FROM
#tmpTable
.
.
.
join with many other tables
select
x.sum_a,
x.sum_b,
x.sum_c,
x.sum_d,
t.id1
from
tmpTable t
join
(
select
id1,
sum(A) as sum_a,
sum(B) as sum_b,
sum(C) as sum_c,
sum(D) as sum_d
from
tmpTable
group by
id1
) x on t.id1 = x.id1
获取第二个。您使用什么分组来获取suma和sumb?那么suma,sumb是按id1,C,D分组的?sumC,sumD是由id1组成的?SumA和SumB不超过id1。还有其他用于它们的id列。对于C和D,我必须使用id1。谢谢你用什么分组来得到suma和sumb?那么suma,sumb是id1,C,D分组的?sumC,sumD是由id1组成的?SumA和SumB不超过id1。还有其他用于它们的id列。对于C和D,我必须使用id1。谢谢
select
x.sum_a,
x.sum_b,
x.sum_c,
x.sum_d,
t.id1
from
tmpTable t
join
(
select
id1,
sum(A) as sum_a,
sum(B) as sum_b,
sum(C) as sum_c,
sum(D) as sum_d
from
tmpTable
group by
id1
) x on t.id1 = x.id1