sql - SQL计算组内不同值的总和和数量
问题描述
我要计算
(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)
解决方案
尝试
SELECT product,
SUM(amount),
COUNT(DISTINCT store)
FROM dbo.temp
GROUP BY product
推荐阅读
- java - 使用密钥库在 Java 中签署 SOAP 请求
- css - 使用此代码时如何使导航栏响应?
- c# - 带有 Syncfustion TabItemControl 的棱镜导航
- flutter - 如何在 Arch Linux 上为 Flutter 2 Web 设置 Google Chrome 的环境变量
- javascript - 高级自定义字段、WordPress、Javascript 选项卡式内容
- android - Unity Remote 5 与 Android 问题:CommandInvokationFailure: Unity Remote 要求检查失败
- firebase - Flutter:CocoaPods 找不到 pod“firebase_analytics”的兼容版本:
- python - 使用术语和正则表达式在 Elasticsearch 中搜索和删除数据的问题
- apache - 将非 www 重定向到 www,SSL ON
- identityserver4 - “AuthenticationScheme:idsrv 未通过身份验证。” 当 Identity Server 4 托管在 IIS 中但工作托管在 Azure 中时