【问题标题】:SQL count occurence of having count > 2 with conditionSQL 计数出现计数 > 2 的条件
【发布时间】:2014-05-19 11:16:35
【问题描述】:

我需要计算表中多行相同值的出现次数。

举个例子

http://sqlfiddle.com/#!6/8ca74/13

有一个具有多列主键的表(A 列 | B 列)。

(fID_a)    |   type
1          |   'type A'
1          |   'type B'
2          |   'type A'
3          |   'type B'
3          |   'type D'
...
9          |   'type A'
9          |   'type B'

我如何计算所有类型组合的出现次数

上述示例的预期结果

type            |     count
'type A'        |     1
'type A type B' |     2
'type B type D' |     1

这仅适用于 A 列中的一次出现

SELECT Count(*) AS count, 
       type 
FROM   tbl_a 
WHERE  fid_a IN (SELECT fid_a 
                 FROM   tbl_a 
                 GROUP  BY fid_a 
                 HAVING Count(*) = 1) 
GROUP  BY tbl_a.type; 

【问题讨论】:

    标签: sql sql-server count having


    【解决方案1】:

    您可以通过使用字符串聚合来为每个 fID_a 值组合它们,然后在该结果上聚合来实现此目的。这在 SQL Server 中有点麻烦,但可能:

    select types, count(*), min(fID_a), max(fID_a)
    from (select fID_a,
                 stuff((select ',' + type
                        from tbl_a a2
                        where a2.fID_a = a.fID_a
                        order by type
                        for xml path ('')
                       ), 1, 1, '') as types
          from tbl_a a
          group by fID_a
         ) t
    group by types;
    

    我添加了其他id 的最小值和最大值,以便您仔细检查结果。

    【讨论】:

    • +1 我认为您还应该在FOR XML PATH 之前添加ORDER BY type 以防止AB - BA 分离。
    • @valex 。 . .谢谢你。确实如此,我们不希望类型的顺序影响结果。
    • order by 需要在 where 子句之后添加才能起作用
    猜你喜欢
    • 2015-05-15
    • 2021-09-06
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多