gpt4 book ai didi

sql-server - 如何计算每个 GroupBy 行(SQL Server)中包含多少行 "rolled up"?

转载 作者:行者123 更新时间:2023-12-02 03:11:59 24 4
gpt4 key购买 nike

我有这个问题:

SELECT TOP 8 M.membername, 
P.MemberNo
FROM prosql05.bidata.dbo.priceexceptionhistorycsr P
JOIN prosql05.cpsdata.dbo.members M
ON P.memberno = M.memberno
WHERE invoicedate BETWEEN '2016-09-04' AND '2016-09-10'
ORDER BY invoicedate

...给我的数据结果如下:

enter image description here

我有这个查询:

SELECT TOP 8 M.membername, 
P.MemberNo
FROM dbo.priceexceptionhistorycsr P
JOIN cpsdata.dbo.members M
ON P.memberno = M.memberno
WHERE invoicedate BETWEEN '2016-09-04' AND '2016-09-10'
and unit = 'FOODBUY'
GROUP BY M.membername, P.Memberno
order by m.membername

...将成员名称组合在一起,以便我得到:

enter image description here

我需要计算每个分组行中代表的行数; IOW,对于上面的数据,我需要查看:

MemberName  MemberNo    Count
---------- -------- -----
Freedom Fresh 110 1
FSA Loveland 028 3

我怎样才能得到它?

最佳答案

只需在Select中添加Count聚合即可

select MemberName, MemberNo, count(1) as [Count]
From
(
--your existing query without Group by
) A
Group by MemberName, MemberNo

也许可以这样简化

SELECT TOP 8 M.membername, 
M.MemberNo,
Count(1) as [Count]
FROM dbo.priceexceptionhistorycsr P
JOIN cpsdata.dbo.members M
ON P.memberno = M.memberno
WHERE invoicedate BETWEEN '2016-09-04' AND '2016-09-10'
and unit = 'FOODBUY'
GROUP BY M.membername, M.Memberno
order by m.membername

为了进一步提高性能,我们可以添加一个非聚集索引

CREATE NONCLUSTERED INDEX IX_members_invoicedate_unit 
ON cpsdata.dbo.members (invoicedate,unit) include (membername,MemberNo)

Index 上面考虑了 invoicedateunit 列来自 cpsdata.dbo.members 表。如果不是,请澄清以进行必要的更改

关于sql-server - 如何计算每个 GroupBy 行(SQL Server)中包含多少行 "rolled up"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39495698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com