1

我有一张桌子Request和一张桌子Search。该Request表有一个 ID 列,它是SearchRequestID 中的外键。Search同一个 RequestID可以有多行。状态中还有另一列Search,它可以是 Complete 或 Incomplete。我想要的是为每个 RequestID 返回的查询:

RequestID- Count of Search rows with 'Complete'-Count of Search rows with 'Incomplete'

这是可以用 SQL 轻松完成的事情吗?

4

1 回答 1

6

尝试 :

SELECT RequestId,
SUM(CASE WHEN Status = 'Complete' THEN 1 ELSE 0 END),
SUM(CASE WHEN Status = 'Incomplete' THEN 1 ELSE 0 END)
FROM Search
GROUP BY RequestId

如果即使没有对此请求进行搜索,您也想列出每个 RequestId,您可以执行以下操作:

SELECT r.Id,
SUM(CASE WHEN s.Status = 'Complete' THEN 1 ELSE 0 END),
SUM(CASE WHEN s.Status = 'Incomplete' THEN 1 ELSE 0 END)
FROM Request r
LEFT JOIN Search s ON r.Id = s.RequestId
GROUP BY r.Id

请参阅SQLFiddle

于 2013-01-13T18:42:07.340 回答