【问题标题】:SQL Count occurrences of multiple columnsSQL Count 多列的出现次数
【发布时间】:2019-10-19 09:49:32
【问题描述】:

我想用按主键分组的多列中的数字 3 的出现次数。 我有一张这样的桌子。

我已经尝试过了。

但我的输出是

但预期的输出是这样的

【问题讨论】:

  • 将代码发布为文本而不是图像...所以我们可以避免重写代码...
  • 这种问题是设计不佳的症状。修改你的架构。

标签: mysql sql database group-by count


【解决方案1】:

有了这个:

select id,
  (s1 = 3) + (s2 = 3) + (s3 = 3) + (s4 = 3) + (s5 = 3) valcount
from tablename

每个布尔表达式:

s? = 3

计算为01

【讨论】:

  • 很好,不需要工会。这应该可以工作,因为 OP 说 ID 是主键
  • Id 是我在图像中看到的主键。所以不需要分组
  • @AdaS 。 . .要使其与您的查询等效,您应该添加having valcount > 0
【解决方案2】:

您的查询一次只计算具有多个三的行。

你可以使用联合:

select  id
,       sum(case when val = 3 then 1 else 0 end)
from    (
        select id, s1 as val from t1
        union all select id, s2 from t1
        union all select id, s3 from t1
        union all select id, s4 from t1
        union all select id, s5 from t1
        ) sub
group by
        id

Example at db-fiddle.com

【讨论】:

  • 但这会返回零作为空值。有没有办法让它们为零
  • 嗯,那么您不能使用where,因为那样会过滤掉所有行。您可以使用仅计算 3 实例的 sum,并在答案中更新。
【解决方案3】:

试试下面的查询..

select id,(count(s1)+count(s2)+count(s3)+count(s4)+count(s5))valcount from(
select id, case when s1=3  then 1 end as s1, 
case when s2=3  then 1 end as s2,
case when s3=3  then 1 end as s3,
case when s4=3  then 1 end as s4,
case when s5=3  then 1 end as s5 
from test) group by id

尝试另一种方式

select id,
count(decode(s1,3,1))+
count(decode(s2,3,1))+
count(decode(s3,3,1))+
count(decode(s4,3,1))+
count(decode(s5,3,1))valcount
from test
group by id

【讨论】:

    【解决方案4】:
    SELECT id,  ( SUM(CASE WHEN s1 =3 THEN  1 ELSE  0 END ) +    SUM(CASE WHEN s2 =3 THEN  1 ELSE  0 END ) +
        SUM(CASE WHEN s3 =3 THEN  1 ELSE  0 END ) +
        SUM(CASE WHEN s4 =3 THEN  1 ELSE  0 END ) +
        SUM(CASE WHEN s5 =3 THEN  1 ELSE  0 END )     ) AS val FROM t1 GROUP BY id
    

    我觉得对你会有帮助

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多