我可以将复杂的选择Where子句重用于不同的组吗?
我在做什么:
(Select X, Count(*) From [Big where clause with many tables] Group By X)
Union All
(Select Y, Count(*) From [Big where clause with many tables] Group By Y)
我如何选择这个?
我正在使用SQL Server 2008,这将进入一个Function,但可能是一个存储过程。
答案 0 :(得分:5)
WITH basequery AS (Select * From [Big where clause with many tables])
SELECT X, COUNT(*) FROM basequery GROUP BY X
UNION ALL
SELECT Y, COUNT(*) FROM basequery GROUP BY Y;
CTE是针对这种情况制作的。
答案 1 :(得分:2)
您可以评估的一个选项(特别是在x,y
组相对较少的情况下)将自己将中间结果实现为@table
或#temp
表,然后{{1}从那里(一个SELECT
表会更好,因为你可以设置比下面更好的索引,它允许填充它的选择查询并行化,但这些在函数中不可用)
#temp
答案 2 :(得分:2)
SQL Server 2008引入了GROUPING SETS ()
,这似乎正是您所追求的。其他人建议的UNION解决方案现在可以通过GROUPING SETS
的单个选择轻松替换。
基本上,你正在使用它:
SELECT A, B, C
FROM …
WHERE …
GROUP BY GROUPING SETS ( (A), (B), (C) )
相当于
SELECT A, NULL, NULL, …
FROM …
WHERE …
GROUP BY A
UNION ALL
SELECT NULL, B, NULL, …
FROM …
WHERE …
GROUP BY B
UNION ALL
SELECT NULL, NULL, C, …
FROM …
WHERE …
GROUP BY C
因此,您的查询可能如下所示:
SELECT X, Y, COUNT(*)
FROM your complex joins and filters
GROUP BY GROUPING SETS ( (X), (Y) )
或者像这样:
SELECT
CASE WHEN X IS NULL THEN 'Y' ELSE 'X' END AS ObjType
CASE WHEN X IS NULL THEN Y ELSE X END AS Obj,
COUNT(*)
FROM your complex joins and filters
GROUP BY GROUPING SETS ( (X), (Y) )
第二个假定X
不能为NULL。
参考文献:
答案 3 :(得分:0)
创建视图
CREATE VIEW SomeView
AS
Select X, Y, Count(*) AS C From [Big where clause with many tables]
然后使用视图:
Select X, C FROM SomeView GROUP BY X