SQL 组合查询
SQL combining queries
目前,我对同一个 table 有两个单独的查询,检查有多少不同的项目。在第一个查询中,我对较大列表中不同项目的数量感兴趣,而在第二个查询中,我只对该列表的一个子集感兴趣。最终我会加入两个输出。
SELECT count(distinct a.item) as items
FROM table a
WHERE a.item in ('01','02','03','04','05','06','07','08','09','10')
SELECT count(distinct a.item) as specific_items
FROM table a
WHERE a.item in ('01','02')
是否可以将其压缩为一个查询?将来我想看看列表的其他子集,而不是添加更多查询和加入更多 tables,我认为必须有一种方法来优化它的可读性和时间。
您可以使用条件聚合:
select
count(distinct a.item) as items,
count(distinct case when a.item in ('01', '02') then a.item end) as specific_items
from table a
where a.item in ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10')
注:item_id
真的是字符串数据类型吗?如果它是一个数字,那么我会建议将它与数字进行比较。如果它是一个整数,那么你可以简化 where
子句如下:
select
count(distinct a.item) as items,
count(distinct case when a.item in (1, 2) then a.item end) as specific_items
from table a
where a.item between 1 and 10
根据您未透露的数据库,可能会有更简洁的解决方案。例如,Postgres 和 SQLite 支持标准的 filter
子句,它允许您将第二个计数重写为:
count(distinct a.item) filter(where a.item in (1, 2)) as specific_items
目前,我对同一个 table 有两个单独的查询,检查有多少不同的项目。在第一个查询中,我对较大列表中不同项目的数量感兴趣,而在第二个查询中,我只对该列表的一个子集感兴趣。最终我会加入两个输出。
SELECT count(distinct a.item) as items
FROM table a
WHERE a.item in ('01','02','03','04','05','06','07','08','09','10')
SELECT count(distinct a.item) as specific_items
FROM table a
WHERE a.item in ('01','02')
是否可以将其压缩为一个查询?将来我想看看列表的其他子集,而不是添加更多查询和加入更多 tables,我认为必须有一种方法来优化它的可读性和时间。
您可以使用条件聚合:
select
count(distinct a.item) as items,
count(distinct case when a.item in ('01', '02') then a.item end) as specific_items
from table a
where a.item in ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10')
注:item_id
真的是字符串数据类型吗?如果它是一个数字,那么我会建议将它与数字进行比较。如果它是一个整数,那么你可以简化 where
子句如下:
select
count(distinct a.item) as items,
count(distinct case when a.item in (1, 2) then a.item end) as specific_items
from table a
where a.item between 1 and 10
根据您未透露的数据库,可能会有更简洁的解决方案。例如,Postgres 和 SQLite 支持标准的 filter
子句,它允许您将第二个计数重写为:
count(distinct a.item) filter(where a.item in (1, 2)) as specific_items