我正在编写一个查询来汇总一些数据。我在表中有一个基本上是布尔值的标志,所以我需要根据它的一个值进行一些求和和计数,然后对另一个值进行同样的操作,如下所示:

select
   location
  ,count(*)
  ,sum(duration)
from my.table
where type = 'X'
  and location = @location
  and date(some_tstamp) = @date
group by location

然后对于类型列的另一个值也是如此。如果我两次加入该表,我仍然如何分组,这样我只能获得每个表的聚合,即计数(a.*) 而不是计数(*)...

编写两个单独的查询会更好吗?

编辑

谢谢大家,但我不是这个意思。我需要分别获得 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

要使计数有效,而不是计数(a。*),只需执行count(a.location)或任何其他非空列(PK将是理想的)。

关于主要问题,上面的shahkalpesh或George Eadon提供的答案中的任何一个都可行。此示例中没有理由将表连接两次。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top