SQL计算组内不同值的总和和数量

时间:2018-12-12 12:52:57

标签: sql sql-server tsql group-by

我要计算

(1)总销售额

(2)每个产品的独立商店数量

在一个查询中,如果可能的话。假设我们有数据:

+-----------+---------+-------+--------+
|   store   | product | month | amount |
+-----------+---------+-------+--------+
| Anthill   | A       |     1 |      1 |
| Anthill   | A       |     2 |      1 |
| Anthill   | A       |     3 |      1 |
| Beetle    | A       |     1 |      1 |
| Beetle    | A       |     3 |      1 |
| Cockroach | A       |     1 |      1 |
| Cockroach | A       |     2 |      1 |
| Cockroach | A       |     3 |      1 |
| Anthill   | B       |     1 |      1 |
| Beetle    | B       |     2 |      1 |
| Cockroach | B       |     3 |      1 |
+-----------+---------+-------+--------+

我没有运气尝试过这个

select 
 [product]
,[month]
,[amount]
,cnt_distinct_stores = count(distinct(stores))
from dbo.temp
group by 
 [product]
,[month]
order by 1,2

GROUP BY子句与SUM(amount) OVER(partition by [product],[month] ORDER BY [month] ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)之类的窗口函数是否可以组合?

1 个答案:

答案 0 :(得分:2)

尝试

SELECT product,
       SUM(amount),
       COUNT(DISTINCT store)
FROM dbo.temp
GROUP BY product