繁体   English   中英

从具有多个where子句的表中获取不同的值计数

[英]Get the distinct count of values from a table with multiple where clauses

我的表结构是这样

id   last_mod_dt     nr     is_u     is_rog     is_ror    is_unv
1       x            uuid1   1         1          1         0
2       y            uuid1   1         0          1         1
3       z            uuid2   1         1          1         1

我想要的行数:

  1. is_ror=1 or is_rog =1
  2. is_u=1
  3. is_unv=1

全部在一个查询中。 可能吗?

我面临的问题是,与上表中的情况一样,nr的值可能相同。

案例陈述提供了灵活性。

SELECT
  sum(case
        when is_ror = 1 or is_rog = 1 then 1
        else 0
      end) FirstCount
 ,sum(case
        when is_u = 1 then 1
        else 0
      end) SecondCount
 ,sum(case
        when is_unv = 1 then 1
        else 0
      end) ThirdCount
 from MyTable

如果“全部查询”不会取消子选择的资格,这听起来很简单。

SELECT 
  (SELECT COUNT(DISTINCT nr) FROM table1 WHERE is_ror=1 OR is_rog=1) cnt_ror_reg,
  (SELECT COUNT(DISTINCT nr) FROM table1 WHERE is_u=1) cnt_u,
  (SELECT COUNT(DISTINCT nr) FROM table1 WHERE is_unv=1) cnt_unv;

您可以使用并集获得多个结果,例如

从is_ror = 1或is_rog = 1的表中选择计数(*)从is_u = 1的表中选择计数(*)从is_unv = 1的表中选择计数(*)

然后结果集将包含三行,每行包含一个计数。

怎么样

SELECT
    SUM(IF(is_u > 0 AND is_rog > 0, 1, 0)) AS count_something,
    ... 
from table
group by nr

我认为它将成功

我当然不确定您到底想要什么,但是我相信您可以使用逻辑来产生想要的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM