用条件查询

时间:2018-07-13 12:00:19

标签: sql sql-server-2012 group-by count

我正在尝试查询“历史记录”表并按“ TypeId”对结果进行分组

我有一列,其中列出了在每个组(计数器)上找到的注册表数量,以计算有多少个注册表,但是如果TypeId = 288被​​发现超过一次,我只想计数1

这是我的查询:

SELECT h.TypeId, t.Description, count(*) as Counter
FROM Hystory h
INNER JOIN HistoryType t on h.TypeId = t.Id
WHERE h.Code in (-- here list of codes)
GROUP BY h.TypeId

在这种情况下,我如何使条件仅计为1?

History:
Id  | TypeId | Code | Date      
1   | 23     | 2222 | xxxx
2   | 233    | 2222 | xxxx
3   | 288    | 2222 | xxxx
4   | 288    | 2222 | xxxx
5   | 23     | 2222 | xxxx
..

HistoryType:
Id  | Description
23  | User add file
233 | User modify file
288 | User access file
..

因此,对于代码= 2222的查询,我想获得:

TypeId | Description     | Counter
23     | User add file   | 2
233    | User edit file  | 1
288    | User access file| 1

4 个答案:

答案 0 :(得分:2)

这是您想要的吗?

SELECT h.Id, h.Date, t.Description,
       ( SUM(CASE WHEN h.TypeId <> 288 THEN 1 ELSE 0 END) +
         MAX(CASE WHEN h.TypeId = 288 THEN 1 ELSE 0 END)            
       ) as Counter

答案 1 :(得分:1)

select sum(A.Counter), A.id FROM(

    SELECT h.Id, count(h.Id) as Counter
    FROM #test_history1 h
    INNER JOIN #test_history2 t on h.TypeId = t.Id
    WHERE h.Code != 288
    GROUP BY h.TypeId, h.Id

    union
    SELECT h.Id, 1 as Counter
    FROM #test_history1 h
    INNER JOIN #test_history2 t on h.TypeId = t.Id
    WHERE h.Code = 288
    GROUP BY h.TypeId, h.Id
    )A
    GROUP BY A.id

答案 2 :(得分:0)

您可以:

select htyp.Id as TypeId, htyp.Description, 
       (case when htyp.Id = 288 then h.Counter1 else h.Counter end) as Counter
from HistoryType htyp cross apply 
    ( select count(*) as Counter, count(distinct h.TypeId) as Counter1
      from History h
      where h.TypeId = htyp.Id
    ) h;

答案 3 :(得分:0)

select ha.typeid,hs.Descr,ha.Counter from (select typeid,count (typeid) Counter  from history group by typeid) as ha
inner join 
(select descr,id from #historytype) as hs on ha.typeid = hs.id