在单个查询中获取多列计数
Get Multi Columns Count in Single Query
我正在开发一个需要在 table 上编写查询的应用程序,这将 return 多个列计入单个查询。
经过研究,我能够为单个 sourceId 开发查询,但是如果我想要多个 sourceId 的结果会怎样。
select '3'as sourceId,
(select count(*) from event where sourceId = 3 and plateCategoryId = 3) as TotalNewCount,
(select count(*) from event where sourceId = 3 and plateCategoryId = 4) as TotalOldCount;
我需要获取多个源 ID 的 TotalNewCount 和 TotalOldCount,例如 (3,4,5,6)
任何人都可以帮忙,我怎样才能将我的查询修改为 return 三列的结果集,包括列表 (3,4,5,6)
中所有来源的数据
谢谢
您可以一次完成所有来源 ID:
select source_id
sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event
group by source_id;
如果您想限制源 ID,请使用 where
(在 group by
之前)。
注意:以上内容适用于 Vertica 和 MySQL,作为标准 SQL 应该适用于任何数据库。
我正在开发一个需要在 table 上编写查询的应用程序,这将 return 多个列计入单个查询。
经过研究,我能够为单个 sourceId 开发查询,但是如果我想要多个 sourceId 的结果会怎样。
select '3'as sourceId,
(select count(*) from event where sourceId = 3 and plateCategoryId = 3) as TotalNewCount,
(select count(*) from event where sourceId = 3 and plateCategoryId = 4) as TotalOldCount;
我需要获取多个源 ID 的 TotalNewCount 和 TotalOldCount,例如 (3,4,5,6)
任何人都可以帮忙,我怎样才能将我的查询修改为 return 三列的结果集,包括列表 (3,4,5,6)
中所有来源的数据谢谢
您可以一次完成所有来源 ID:
select source_id
sum(case when plateCategoryId = 3 then 1 else 0 end) as TotalNewCount,
sum(case when plateCategoryId = 4 then 1 else 0 end) as TotalOldCount
from event
group by source_id;
如果您想限制源 ID,请使用 where
(在 group by
之前)。
注意:以上内容适用于 Vertica 和 MySQL,作为标准 SQL 应该适用于任何数据库。