如何计算每行另一列值的不同出现次数

时间:2013-12-19 16:15:26

标签: sql select count group-by

我正在寻找一种有效计算每个ID子码的方法:

 ID     |      subvalue
 001    |      056
 001    |      093
 001    |
 002    |      054
 002    |      033
 003    |      
 003    |      012
 003    |      094
 003    |      008
 004    |      

导致:

ID     |      Count
001    |      2
002    |      2
003    |      3
004    |      0

和等价的唯一值:

轻微添加:

  ID     |      subvalue
  001    |      001
  001    |      001
  001    |      
  002    |      002
  002    |      002
  003    |      
  003    |      003
  003    |      003
  003    |      003
  004    |  

导致:

 ID     |      Count
 001    |      2
 002    |      2
 003    |      3
 004    |      0

3 个答案:

答案 0 :(得分:2)

这是基本的SQL,您可以按所需的项目进行分组,并使用聚合函数count()

select id, count(subvalue) as count
from table
group by id

如果指定字段名,则Count不会计算空值。

如果你有(不是这种情况)你不想计算的空字符串(或其他一些标准)你可以将它放在where子句中或使用一个案例,如下所示:

select id, sum(CASE stringValue = '' THEN 0 ELSE 1 END) as count
from table
group by id

答案 1 :(得分:0)

DECLARE @T TABLE (ID VARCHAR(10), SubValue VARCHAR(10))

INSERT INTO @T
VALUES ('001','056'),('001','093'),('001',NULL),('002','054'),
('002','033'),('003',NULL),('003','012'),('003','094'),
('003','008'),('004',NULL)

SELECT A.ID, ISNULL(COUNT(A.ID), 0) Total
FROM @T A LEFT JOIN @T B
ON A.ID = B.ID AND A.SubValue = B.SubValue
WHERE B.SubValue IS NOT NULL
GROUP BY A.ID

<强>结果

╔═════════╦═══════╗
║     ID  ║ Total ║
╠═════════╬═══════╣
║     001 ║     2 ║
║     002 ║     2 ║
║     003 ║     3 ║
╚═════════╩═══════╝

或者,如果你想要返回4个id,你也可以做这样的事情

SELECT DISTINCT A.ID, COALESCE(Total, 0) Total
FROM @T A LEFT JOIN (SELECT ID, COUNT(ID) AS Total
                   FROM @T
                   WHERE SubValue IS NOT NULL
                   GROUP BY ID) C
ON A.ID = C.ID

<强>结果

╔═════════╦═══════╗
║     ID  ║ Total ║
╠═════════╬═══════╣
║     001 ║     2 ║
║     002 ║     2 ║
║     003 ║     3 ║
║     004 ║     0 ║
╚═════════╩═══════╝

SELECT ID, SUM(CASE WHEN SubValue IS NULL THEN 0 ELSE 1 END) as [COUNT]
FROM @T
GROUP BY ID

答案 2 :(得分:0)

您是否只想分组并排除空白?

没有运行它,但我认为这样的事情应该让你到那里:

Select ids. ID, Coelesce(counts.value, 0)

(Select Distinct ID
 From TableName) as ids

left join

    (Select ID, Count(subvalue) as value
    From TableName
    Where value is not null 
     And value != ''
    Group By ID) as counts

on ids.id = counts.id