0

我有以下 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

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

这是为什么?

4

1 回答 1

1

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

因此,第二部分中的第五和第六列(您给它们提供别名A3DuplexPagesPrintedand A3DuplexTotalCost)将填充到结果的第五和第六列中并命名为A3PagesPrintedand 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
于 2013-10-21T05:03:56.330 回答