【问题标题】:Query with condition on Count使用 Count 条件查询
【发布时间】:2018-12-21 19:21:02
【问题描述】:

我正在尝试对我的“历史”表进行查询并按“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
..

所以,对于 code = 2222 的查询,我想得到:

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

【问题讨论】:

  • 帮助我们帮助您 - 请发布表格的结构、一些示例数据以及您希望为此示例获得的结果。
  • (1) 用您正在使用的数据库标记您的问题。 (2) 样本数据和期望的结果会很有帮助。
  • 该查询似乎是错误的......它如何让您仅按 TypeId 进行分组,同时在 select 中声明了 Date 和 Description 字段?
  • @Mureinki 添加了更多信息

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


【解决方案1】:
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

【讨论】:

  • 虽然这段代码可以回答这个问题,但它缺乏解释。请考虑添加文字来解释它的作用,以及它为什么回答所提出的问题。
【解决方案2】:
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

【讨论】:

    【解决方案3】:

    你可以这样做:

    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;
    

    【讨论】:

      【解决方案4】:

      这是你想要的吗?

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-11
        • 2023-03-27
        • 2022-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-07
        相关资源
        最近更新 更多