GROUP BY +不同的记录数

时间:2018-07-17 05:51:06

标签: sql sql-server group-by

请考虑以下数据:

Id        StateCode           PersonCode           Feature1
-----------------------------------------------------------
1             1                 2000                 10          
2             1                 2000                 13      
3             1                 3000                 20      
4             2                 2000                 1      
5             2                 2000                 13      
6             2                 4000                 10      
7             2                 4000                 11      
8             2                 5000                 10      
9             2                 5000                 1      
10            3                 2000                 10      
11            3                 3000                 9      
12            3                 3000                 1      
13            3                 3000                 4     

我想得到来自distinct StateCode & PersonCode

的结果
Count       StateCode
  2            1
  3            2
  2            3

我写了这个查询:

SELECT COUNT(*) AS Count,aa.StateCode
FROM   
     (select distinct StateCode, PersonCode
      from @tbl) aa
GROUP BY aa.StateCode

如何用一个查询和分组依据编写此查询?

,如果可能的话,如何使用一个LINQ查询来编写此查询?

谢谢

4 个答案:

答案 0 :(得分:0)

您可以将查询写为:-

select count(distinct PersonCode) , StateCode from @tbl group by StateCode ;

希望这对您有帮助!

答案 1 :(得分:0)

尝试GroupBy

class StateCodeCount
{
    public int Count {get; set;}
    public int StateCode {get; set;}
}

var result = datatableStateCode
    .GroupBy(c => c.StateCode )
    .Select(c => new StateCodeCount
    {
        StateCode = c.Key,
        Count= x.Where(g => g.StateCode== c.Key)
                .Select(t => t.PersonCode)
                .Distinct()
                .Count()
    })
    .ToList();

答案 2 :(得分:0)

select count(DISTINCT PersonCode) , StateCode from @tbl group by StateCode ;

DISTINCT COUNT(*)将为每个唯一计数返回一行。您想要的是COUNT(DISTINCT expression):为组中的每一行求值表达式,并返回唯一的非空值的数量。

ref:https://stackoverflow.com/a/1521656/2750968

答案 3 :(得分:0)

如果您的数据库服务器支持窗口功能,那么这里是一个解决方案:

http://sqlfiddle.com/#!4/33986d/3

SELECT DISTINCT StateCode, COUNT(DISTINCT PersonCode) OVER (PARTITION BY StateCode) AS "Count" from @tbl ORDER BY StateCode;