如何查询和组合具有不同条件的列到一个表/视图中?

时间:2017-01-05 23:47:41

标签: sql sql-server sql-server-2008 relational-database

以下是示例:让我说我有杂志订阅。我有杂志A,B,C。每个月我都想知道我有多少订阅者获得,丢失和每本杂志的总数。我希望能够按月,年搜索。 我想以这种方式显示数据:

Mag  |Total|New|Lost|
--------------------- 
MagA | 25  | 7 |  1 |

MagB | 32  | 3 |  6 |

MagC | 65  | 4 |  2 |

所以这就是我所做的:

CREATE FUNCTION fn_MemberCount(@Month INT, @Year INT)
  RETURNS TABLE AS
RETURN
(
WITH M AS
(
SELECT
  Mag, MagID, COUNT(M.UserID) 'Count', 'New' AS 'Change'
FROM Members as M JOIN Mags as B
  ON M.MagID = B.MemberID
WHERE Month(M.JoinDate) = @Month 
  AND YEAR(M.Joindate) = @Year 
GROUP BY B.MagID ,B.Mag

UNION ALL

SELECT
  Mag, MagID, COUNT(M.UserID) 'Count', 'Closed' AS 'Change'
FROM Members as M JOIN Mags as B
  ON M.MagID = B.MemberID
WHERE Month(M.CancelDate) = @Month 
  AND YEAR(M.CancelDate) = @Year 
GROUP BY B.MagID, B.Mag
),
PivotData AS
(
SELECT
  MagID, Mag, Change, [Count]
FROM M
)
SELECT MagID, Mag, [New], [Closed]
FROM PivotData
  Pivot (SUM([Count])
   For Change IN ([New], [Closed])) AS P
);

我使用了一个联盟,因为他们对新订阅和取消订阅的标准是不同的,这似乎是最合乎逻辑的方式。 该功能是能够简单地添加年份和月份并以这种方式过滤结果。如果我需要进一步自动化,我可能会把它放在存储过程中。

是否有更好的方法可以获得相同的结果?以不同的方式为每列提供不同的搜索条件?

(我知道上面的代码没有生成第一个Total列。为此,我会创建另一个UNION ALL但我想在花更多时间之前向社群提出建议此)

非常感谢任何建议或建议!

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合来简化查询。您遇到的where条款将是您汇总的条件。

SELECT
  B.Mag
 ,B.MagID 
 ,COUNT(M.USERID)  as Total
 ,COUNT(CASE WHEN Month(M.JoinDate) = @Month AND YEAR(M.Joindate) = @Year THEN 1 END) AS New
 ,COUNT(CASE WHEN Month(M.CancelDate) = @Month AND YEAR(M.CancelDate) = @Year THEN 1 END) AS Cancel
FROM Members as M 
JOIN Mags as B ON M.MagID = B.MemberID
GROUP BY B.MagID,B.Mag