SQL Group By Range

时间:2014-09-19 23:45:44

标签: sql sql-server

我们有两列First_Issue和Expiry_Issue

如果我想知道问题有多少订阅者,我会进行如下查询:

select COUNT(*) from Subscriber 
where First_issue <= 1 and Expiry_issue >= 1 

现在我想编写一个查询,向我展示每个问题的订阅者数量,不确定从哪里开始,任何指针都赞赏。

1 个答案:

答案 0 :(得分:1)

如果您未在issues表中提供所有问题编号,则可以按以下方式生成:

WITH Issues AS (
  SELECT 1 as Number
  UNION ALL
  SELECT Number + 1 as Number
  FROM Issues WHERE Number + 1 <= (SELECT MAX(Expiry_Issue) FROM Subscriber)
)
SELECT issue.Number, COUNT(DISTINCT s.id)
FROM 
  Subscriber s INNER JOIN 
  Issues i ON i.Number BETWEEN s.First_Issue AND s.Expiry_Issue