-1

我有一个可以通过以下方式链接多个子记录的表:

 table object:

 id    description   type

其中 id 是主键。

我有另一个表,事件具有作为外键的对象 id

table event

id  object_id status  description

status 字段的值可以是 0 或 1,表示它是否处于挂起状态

我需要在一个查询中获取所有对象以及未决事件的数量以及未处理的事件数量

例如:

Object record:

id    description    type
---- ------------- ------
1    Printer        hardware

相关事件记录

Event records

id   object_id     status    description
---- ---------    --------   --------------
1    1            0           Ordered
2    1            0           Shipped
3    1            1           Received by customer

预期的结果是

  object_id    pending_events      completed_events
  ----------- -----------------   -----------------
  1            1                  2 

谢谢

4

5 回答 5

3

你可以用COUNT这个。如果COUNT参数为空,则不计算行数;如果参数是非空的,它会。

SELECT
  object_id,
  COUNT(CASE WHEN status = 1 THEN 1 ELSE NULL END) AS pending_events,
  COUNT(CASE WHEN status = 0 THEN 1 ELSE NULL END) AS completed_events
FROM Event
GROUP BY object_id

请注意,这THEN 1只是指定一个非空值;它可能是THEN 'a'orTHEN 'apples'THEN 'oranges'. 关键是非空值被统计;空值不是。

于 2013-08-07T19:53:33.170 回答
3

您可以使用条件聚合来做到这一点:

select  e.object_id,
        sum(case when status = 1 then 1 else 0 end) as pending_events,
        sum(case when status = 0 then 1 else 0 end) as completed_events
from events e
group by e.object_id;

如果 status 只取 0 和 1 的值,您实际上可以将其简化为:

select  e.object_id,
        sum(status) as pending_events,
        sum(1-status) as completed_events
from events e
group by e.object_id;
于 2013-08-07T19:53:41.140 回答
0
SELECT  O.ID AS OBJECT_ID
        ,SUM(CASE WHEN E.STATUS = 1 THEN 1 ELSE 0 END) AS PENDING_EVENTS
        ,SUM(CASE WHEN E.STATUS = 0 THEN 1 ELSE 0 END) AS COMPLETED_EVENTS
FROM    OBJECT O    
LEFT OUTER JOIN
        EVENT E
ON      O.UD = E.OBJECT_ID
GROUP BY
        O.ID
于 2013-08-07T19:53:21.140 回答
0
select object_id,
       sum(case when status = 1 then 1 else 0 end) as pending_events,
       sum(case when status = 0 then 1 else 0 end) as completed_events
from [Event Records]
group by object_id
于 2013-08-07T19:53:31.360 回答
0

这是SQLFiddle

SELECT
  obj_id,
  COUNT(CASE WHEN status = 1 THEN 1 ELSE NULL END) AS pending_events,
  COUNT(CASE WHEN status = 0 THEN 1 ELSE NULL END) AS completed_events
FROM Event
GROUP BY obj_id
于 2013-08-07T19:54:18.297 回答