如果可能的话,我正在寻找一种方法仅在一个查询中使用动态分组条件总结值。这也意味着不 UNION ALL
。
(下面的查询非常简单,UNION ALL
根本不会很昂贵,但是如果必须从一堆表中收集源数据,则会降低性能以完成所有连接两次。)
示例数据:
create table data (id int, location nvarchar(1), qty int, grouping tinyint)
insert into data (id, location, qty, grouping) values (1, 'A', 10, 0)
insert into data (id, location, qty, grouping) values (1, 'A', 20, 0)
insert into data (id, location, qty, grouping) values (1, 'B', 15, 0)
insert into data (id, location, qty, grouping) values (2, 'A', 5, 1)
insert into data (id, location, qty, grouping) values (2, 'B', 10, 1)
insert into data (id, location, qty, grouping) values (3, 'B', 20, 1)
如果分组为0,则每个位置应该总计数量,否则每个id。
估算结果:
1, A, 30
1, B, 15
2, null, 15
3, null, 20
请参阅SQL-Fiddle
答案 0 :(得分:0)
可以使用CASE WHEN ...
SELECT id ,
(CASE WHEN grouping = 0 THEN location ELSE NULL END) AS location,
SUM(qty) AS qty
FROM data
GROUP BY id ,(CASE WHEN grouping = 0 THEN location ELSE NULL END)
ORDER BY id
结果:
id location qty
1 A 30
1 B 15
2 NULL 15
3 NULL 20