sql - 根据 where 语句从子查询中选择多个结果计数?
问题描述
因此,我从子查询中进行选择,并根据创建的列中的值是否具有值来显示这些行的计数(使用 where 语句)。
我想创建一个查询,该查询根据不同的 where 语句返回多个计数。
我的表有两列:ID1 和 abc2。
select count(*) from
(
select `id1`, count(distinct(`abc2`)) as total_abc
from TABLE
where `id1` != 'Unknown' and `abc2` != 'NULL'
group by `id1`
order by total_abc desc
)
where total_abc = 1
select count(*) from
(
select `id1`, count(distinct(`abc2`)) as total_abc
from TABLE
where `id1` != 'Unknown' and `abc2` != 'NULL'
group by `id1`
order by total_abc desc
)
where total_abc = 2
select count(*) from
(
select `id1`, count(distinct(`abc2`)) as total_abc
from TABLE
where `id1` != 'Unknown' and `abc2` != 'NULL'
group by `id1`
order by total_abc desc
)
where total_abc = 3
所需的结果只需结合以下几个查询:
count1 | count2 | count3
__________________________
123 | 222 | 34567
解决方案
您可以使用两个级别的聚合:
select
count(case when num_vals = 1 then 1 end) as val_1,
count(case when num_vals = 2 then 1 end) as val_2,
count(case when num_vals = 3 then 1 end) as val_3
from
(
select id1, count(distinct abc2) as num_vals
from TABLE
where id1 <> 'Unknown' and abc2 <> 'NULL'
group by id1
) t;
您似乎想要列中的值。我希望它们成行:
select num_vals, count(*)
from (select id1, count(distinct abc2) as num_vals
from TABLE
where id1 <> 'Unknown' and abc2 <> 'NULL'
group by id1
) t
group by num_vals
order by num_vals;
推荐阅读
- python - 检查一列是否包含来自其他列的值并填充第三列(真或假)
- php - PHP 从多个 HTML 复选框更新 SQL
- c++ - 将检测到的 2D 地图调整为参考 2D 地图
- angularjs - 日期选择器在 angularjs ng-template 脚本中不起作用
- javascript - 比较两个嵌套对象数组
- react-native - React Native - 动画视图在 Android 上摇摇欲坠
- vuejs2 - Vue2.js - 在自定义插件中使用自定义组件 - 如何传递道具?
- react-native - 我如何将文件从 react native 上传到 .net core api
- ios - 检测具有良好对比度和纹理的图像
- ios - Cordova iOS 应用程序以 iOS 7 风格运行