我有以下示例数据:
ID | SectionID | LocID
1 32 12
1 32 2
1 32 2
1 34 3
1 34 4
2 36 8
2 36 9
2 37 8
2 37 9
2 37 4
输出应按ID分组。 Count LocID字段应显示 每个sectionID的DISTINCT LocID数量总计。
对于ID为1,对于SectionID 32,我们有2个不同的LocID,对于SectionID 34,我们有2个。总计等于4
对于ID为2,对于SectionID 36,我们有2个不同的LocID;对于ID为37,我们有3个。总计等于5
结果:
ID Count
1 4
2 5
我按ID进行了分组,但不确定如何根据需要进行进一步分组。我正在使用SQL Server2016。
答案 0 :(得分:4)
我认为,最简单的方法是按您的ID分组,并在SectionID和LocID的串联中进行不同的计数。如果这些是字符数据,则只需将其与某种分隔符串联即可避免。如果它们是数字,则可以执行以下示例,或将它们转换为字符串并使用定界符concat。
-------------------------
-- set up sample data
-------------------------
declare @datatable as table(ID int, SectionID int, LocID int)
insert into @datatable(ID, SectionID, LocID) VALUES
(1,32,12 ),
(1,32,2 ),
(1,32,2 ),
(1,34,3 ),
(1,34,4 ),
(2,36,8 ),
(2,36,9 ),
(2,37,8 ),
(2,37,9 ),
(2,37,4 )
-------------------------
-- The query
-------------------------
SELECT
ID
,COUNT (DISTINCT SectionID * 10000 + LocID)
FROM
@datatable
GROUP BY ID
给出结果:
(10 row(s) affected)
ID
----------- -----------
1 4
2 5
(2 row(s) affected)
答案 1 :(得分:2)
您可以使用嵌套的分组依据,例如
SELECT ID, SUM([Count])
FROM
(
SELECT ID, SectionID, COUNT(DISTINCT LocID) AS [Count]
FROM Table
GROUP BY ID, SectionID
) Q
GROUP BY ID
答案 2 :(得分:0)
一种肮脏而肮脏的方法是仅嵌套您的分组。
DECLARE @t TABLE
(
ID INT,
SectionID INT,
LocID INT
);
INSERT INTO @t
(
ID
,SectionID
,LocID
)
VALUES
( 1,32,12),
( 1,32,2),
( 1,32,2),
( 1,34,3),
( 1,34,4),
( 2,36,8),
( 2,36,9),
( 2,37,8),
( 2,37,9),
( 2,37,4)
SELECT
d.ID
,SUM(d.LocIDs) AS LocIDCnt
FROM
(
SELECT
ID
,SectionID
,COUNT(DISTINCT LocID) AS LocIDs
FROM
@t
GROUP BY
ID
,SectionID
) AS d
GROUP BY
d.ID;
结果集:
+----+-------+
| ID | Count |
+----+-------+
| 1 | 4 |
| 2 | 5 |
+----+-------+
答案 3 :(得分:0)
另一种方式:
select ID, COUNT(*) as SecLocCount
from (
select distinct ID, SectionID, LocID from [MyTable]
) AS distinctRows
group by ID