我正在编写一个查询来总结一些数据.我在表中有一个基本上是布尔值的标志,所以我需要基于它的一个值的一些总和和计数,然后对于另一个值则需要相同的东西,如下所示:
select location ,count(*) ,sum(duration) from my.table where type = 'X' and location = @location and date(some_tstamp) = @date group by location
然后相同的类型列的另一个值.如果我两次加入这个表,我怎么仍然分组,所以我只能得到每个表的聚合,即count(a.*
)而不是count(*)...
写两个单独的查询会更好吗?
编辑
谢谢大家,但这不是我的意思.我需要得到一个摘要,其中type ='X'和一个摘要,其中type ='Y'分开...让我发布一个更好的例子.我的意思是这样的查询:
select a.location ,count(a.*) ,sum(a.duration) ,count(b.*) ,sum(b.duration) from my.table a, my.table b where a.type = 'X' and a.location = @location and date(a.some_tstamp) = @date and b.location = @location and date(b.some_tstamp) = @date and b.type = 'Y' group by a.location
我需要分组什么?此外,DB2不喜欢count(a.*
),这是一个语法错误.
select
location
,Sum(case when type = 'X' then 1 else 0 end) as xCount
,Sum(case when type = 'Y' then 1 else 0 end) as YCount
,Sum(case when type = 'X' then duration else 0 end) as xCountDuration
,Sum(case when type = 'Y' then duration else 0 end) as YCountDuration
from my.table
where
location = @location
and date(some_tstamp) = @date
group by location
这应该在SQL Server中工作.我想db2应该有类似的东西.
编辑:添加where条件以限制记录以选择type = X或type = Y,如果"type"可以具有X和Y以外的值.
你的连接示例没有多大意义.你在A和B之间做笛卡尔积.这真的是你想要的吗?
以下将找到满足WHERE子句的每对的count(*)和sum(duration).根据您的描述,这听起来像您正在寻找的:
select type ,location ,count(*) ,sum(duration) from my.table where type IN ('X', 'Y') and location = @location and date(some_tstamp) = @date group by type, location