我需要做一个查询,根据用户输入条件从表中选择一个分组的行集合,然后在select中,我将从行子集中求和数据。
在一篇文章中描述这个设置是相当广泛的,所以这里用我能做到的最简单的方式来演示这个问题:
我们有这个表:DemoTable
<表类>
ID
StaticKey
GroupKey
价值
tbody><<tr>1 2 22 3 B 2 4B 2 5C 2 6C 2 表类>
更简单:
select GroupKey,
sum(Value) as sum_of_A,
sum(GroupKey='A') as count_of_A
from DemoTable
where GroupKey='A'
group by GroupKey;
https://dbfiddle.uk/sdYlTw57
不总是D.ID in (DT.ID)
吗?
select
DT.GroupKey,
(select sum(D.Value) from DemoTable D where D.GroupKey = 'A') as 'Sum of A''s',
(select COUNT(D.ID) from DemoTable D where D.GroupKey = 'A') as 'Count of A''s'
from DemoTable DT
group by DT.StaticKey;
它的工作,但可能是太简单了…
你也可以试试这个
SELECT DT.GroupKey,
SUM(DT.Value) AS 'Sum of A''s',
COUNT(DT.ID) AS 'Count of A''s'
FROM DemoTable DT
WHERE DT.GroupKey = 'A'
GROUP BY DT.StaticKey;