SQL Server 分组依据和计数

问题描述 投票:0回答:1

我正在尝试按地区内的国家/地区进行发票计数。下面是我的表结构和所需输出的视图。我尝试对此进行基本视图(尚未查看 CustomerArea,因为我想先了解基本知识),但无法进入嵌套模式。

SELECT Customerregion, COUNT(InvoiceNo ) AS CountCol1
FROM [Data-Warehouse].[dbo].[Master]
WHERE Customerregion='Europe'
GROUP BY Customerregion, InvoiceNo

以下是仅基于上述内容的欧洲产出视图?

CustomerArea    CustomerRegion  InvoiceNo
Romania Europe  INV001
Romania Europe  INV002
Netherlands Europe  INV003
Netherlands Europe  INV003
Netherlands Europe  INV003
Netherlands Europe  INV004
Italy   Europe  INV005
Italy   Europe  INV005

sql sql-server
1个回答
1
投票

我想你所需要的就是这个。获得此数据后,您可以计算某个区域的总数,并在调用代码中进行总计。

DROP TABLE IF EXISTS #DataTable;

CREATE TABLE #DataTable (
    CustomerArea VARCHAR(20),
    CustomerRegion VARCHAR(20),
    InvoiceNo VARCHAR(6)
);

INSERT INTO #DataTable (CustomerArea, CustomerRegion, InvoiceNo)
VALUES
('Romania', 'Europe', 'INV001'),
('Romania', 'Europe', 'INV002'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV003'),
('Netherlands', 'Europe', 'INV004'),
('Italy', 'Europe', 'INV005'),
('Italy', 'Europe', 'INV005');

SELECT CustomerRegion, CustomerArea, COUNT(*) AS NumberOfInvoices
FROM #DataTable
GROUP BY CustomerArea, CustomerRegion
© www.soinside.com 2019 - 2024. All rights reserved.