我对UNION条款有几个问题 我想过滤一个字段的总结果。 一个想法是过滤每个查询,但它可能是"硬"什么都不做。
SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
--WHERE LicenseCode > 7878
显然,最终的陈述并不奏效。
如何过滤总UNION结果? (不要在每个查询中加上语句(WHERE LicenseCode > 7878
)。
谢谢! 此致
答案 0 :(得分:6)
首先,请勿使用UNION
,请使用UNION ALL
。 UNION
会产生额外的开销,用于删除重复项。
其次,你的问题的答案是使用子查询或CTE:
SELECT t.*
FROM ((SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
) UNION ALL
(SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
) UNION ALL
(SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
)
) t
WHERE LicenseCode > 7878;
SQL Server有一个智能优化器。我很确定它将WHERE
子句推送到各个子查询。这是一项重要的优化。在不这样做的数据库中,您需要重复WHERE
条件。
注意:如果您从同一个表中进行选择,则有更好的方法来编写查询:
select grp, t.licensecode, t.field2, t.field3, t.field4
from table t cross apply
(values ('group1'), ('group2'), ('group3')) g(grp)
where licensecode > 7878;
答案 1 :(得分:3)
使联合成为子查询,然后过滤结果:
select group, LicenseCode, Field2, Field3, Field4
from (
SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
) x
WHERE LicenseCode > 7878
答案 2 :(得分:0)
如果您只想按任意顺序对结果进行排序,那么您只需要通过语句为联合中的最后一个选择进行排序。默认情况下,它会为您整理整个结果。所以看起来应该是这样的
SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
ORDER BY YourColumnName
但是从这里开始,您还希望根据列过滤记录。请试试这个
;WITH CTE
AS
(
SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
)
SELECT
*
FROM CTE
WHERE LicenseCode > 7878
ORDER BY Your Columnname
答案 3 :(得分:0)
利用CTE。
; WITH CTE AS
(
SELECT 'GROUP1' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP2' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
UNION
SELECT 'GROUP3' AS GROUP, LicenseCode, Field2, Field3, Field4
FROM TABLE
)
select * from CTE WHERE LicenseCode > 7878