按唯一ID对SQL中的子查询进行分组

时间:2019-06-12 23:47:29

标签: 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     |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       |
+---------+------+------+---------+---------+

3 个答案:

答案 0 :(得分:1)

由于您对A和B具有不同的分组条件,因此可以将它们分别分组为C和D。下面的内容(使用通用表表达式)可能使您踏上正确的路:

    ; with SummaryValues AS
    (
        select id1, sum(C) as SumC, SUM(D) as SumD
        from #SourceTable
        group by id1
    )
    select SUM(st.A), SUM(st.b), sv.SumC, sv.SumD, st.id1
    from #SourceTable st
    inner join SummaryValues sv
        on st.id1 = sv.id1
    group by <whatever grouping you are using>

答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果您当前的实际查询是以您想要的方式总结ab并生成第一个示例输出,则可能类似于:

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

获得第二个。