按id排除出现次数

时间:2013-12-04 21:10:17

标签: sql sql-server sql-server-2008

是否可以计算表中值出现的次数,但是,如果每个id出现多次值,则使用计数为1。

以下表为例。我们想知道p_id是否发生了{5,6}。如果发现{5,6}超过1次,则将其视为1.例如。 p_id 1,总计数为1.

p_id        status
 1             5
 1             6
 1             2
 2             5
 2             5
 3             4
 3             2
 4             6
 4             2
 4             5

..转换为..

p_id        count
 1             1          
 2             1
 3             0
 4             1

COUNT(CASE状态IN(5,6)那么1 END)总计数。

4 个答案:

答案 0 :(得分:2)

使用CASE...WHEN...,如下所示:

SELECT a.id, ISNULL(b.cnt, 0)
FROM 
    (
        SELECT DISTINCT id FROM tab
    ) a
    LEFT JOIN 
    (
         SELECT id, CASE COUNT(*) WHEN 1 THEN 0 ELSE 1 END 'cnt' 
         FROM tab WHERE val in (5, 6) GROUP BY id
    ) b
   ON a.id = b.id

SQLFiddle

答案 1 :(得分:0)

使用您的示例,此解决方案提供了快速设置和我如何执行此操作的简单两步说明。第二个查询提供了所需的结果:

CREATE TABLE #temp (p_id INT, [status] INT); 
INSERT #temp VALUES (1,5);
INSERT #temp VALUES (1,6);
INSERT #temp VALUES (1,2);
INSERT #temp VALUES (2,5);
INSERT #temp VALUES (2,5);
INSERT #temp VALUES (3,4);
INSERT #temp VALUES (3,2);
INSERT #temp VALUES (4,6);
INSERT #temp VALUES (4,2);
INSERT #temp VALUES (4,5);

-- Simple two-step tutorial
-- First, group by p_id so that all p_id's will be shown 
-- run this to see...
SELECT A.p_id
FROM #temp A
GROUP BY A.p_id;

-- Now expand your query
-- Next, for each p_id row found, perform sub-query to see if 1 or more exist with status=5 or 6
SELECT A.p_id
    ,CASE WHEN EXISTS(SELECT 1 FROM #temp B WHERE B.p_id=A.p_id AND [status] IN (5,6)) THEN 1 ELSE 0 END AS [Count]
FROM #temp A
GROUP BY A.p_id;

答案 2 :(得分:0)

使用SIGN()功能。这正是你要找的。

SELECT
  [p_id],
  SIGN(COUNT(CASE WHEN [status] IN (5,6) THEN 1 END)) AS [count]
FROM #temp
GROUP BY p_id

答案 3 :(得分:0)

您可以翻译5,6 = 1并将其休息为0然后执行max()

with cte as (
  select p_id, case when status in (5,6) then 1 else 0 end status
  from FROM #tem)

select p_id, max(status) status
from cte
group by p_id