Sql 联合查询未显示第二次查询的记录
我有以下SQL查询:Sql 联合查询未显示第二次查询的记录,sql,sql-server,union,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
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
现在,两个查询在单独运行时都返回值。但当我同时执行它们时,第二个查询的记录显示为一个DuplexPageSprint和一个DuplexTotalCost
为什么会这样?联合查询将从查询的第一部分获取列名,并以相同的顺序将所有后续部分填充到这些列中,而不考虑名称或别名
因此,第二部分中的第五列和第六列(别名A3DuplexPagesPrinted和A3DuplexTotalCost)将填入结果的第五列和第六列,并命名为A3PagesPrinted和A3TotalCost(别名来自第一个SELECT子句)
如果要区分两个查询中的列,则必须为查询的每个部分指定所有列注意下面的空值:
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
实际上,我的表不包含A3PageSprint A3TotalCost A3DuplexPageSprint A3DuplexTotalCost列。这些是基于where子句中定义的条件的用户定义的列。这很好,但如果您希望将数据分隔开,则必须指定所有跨行的列。我假设这是动态生成的SQL