Union Query不显示第二个查询的记录

时间:2013-10-21 04:58:52

标签: sql sql-server union

我有以下SQL查询:

select (case when len(GroupName) = 0 then 'Unknown' else GroupName end) as GroupName 
,PaperId,Color,Duplex, sum(Page_Printed) As A3PagesPrinted, sum(Cost) as A3TotalCost 
from printstat where paperid = 8 and color = 0 and duplex = 0 
and Date_Print >= '2013-01-01' and Date_Print < '2013-10-21'
group by GroupName, PaperId, Color, Duplex

union all

select (case when len(GroupName) = 0 then 'Unknown' else GroupName end) as GroupName
,PaperId,Color,Duplex, sum(Page_Printed) As A3DuplexPagesPrinted, 
sum(Cost) as A3DuplexTotalCost from printstat where paperid = 8 and color = 0 
and duplex = 1 and Date_Print >= '2013-01-01' and Date_Print < '2013-10-21'
group by GroupName, PaperId, Color, Duplex

现在,两个查询在单独运行时都会返回值。但是当我一起执行它们时,我会显示第二个查询的记录A3DuplexPagesPrintedA3DuplexTotalCost

为什么?

1 个答案:

答案 0 :(得分:1)

UNION查询将从查询的第一部分获取列名,并以相同的顺序将所有后续部分填充到这些列中,无论名称或别名

因此,第二部分的第五和第六列(您为其提供别名A3DuplexPagesPrintedA3DuplexTotalCost)将填入结果的第五和第六列,并命名为A3PagesPrinted并且A3TotalCost(第一个SELECT子句中的别名)。

如果要区分两个查询中的列,则必须为查询的每个部分指定所有列(请注意下面的NULL):

select case when len(GroupName) = 0 then 'Unknown' else GroupName end as GroupName,
    PaperId,
    Color,
    Duplex, 
    sum(Page_Printed) As A3PagesPrinted, 
    sum(Cost) as A3TotalCost,
    NULL AS A3DuplexPagesPrinted,
    NULL AS A3DuplexTotalCost
from printstat where paperid = 8 and color = 0 and duplex = 0 
and Date_Print >= '2013-01-01' and Date_Print < '2013-10-21'
group by GroupName, PaperId, Color, Duplex

union all

select case when len(GroupName) = 0 then 'Unknown' else GroupName end as GroupName,
    PaperId,
    Color,
    Duplex,
    NULL,
    NULL,
    sum(Page_Printed) As A3DuplexPagesPrinted, 
    sum(Cost) as A3DuplexTotalCost
from printstat where paperid = 8 and color = 0 
and duplex = 1 and Date_Print >= '2013-01-01' and Date_Print < '2013-10-21'
group by GroupName, PaperId, Color, Duplex