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

個別に実行すると、両方のクエリが値を返すようになりました。しかし、それらを一緒に実行すると、2 番目のクエリのレコードが表示されA3DuplexPagesPrintedA3DuplexTotalCost.

何故ですか?

4

1 に答える 1

1

クエリは、クエリのUNION最初の部分から列名を取得し、名前やエイリアスに関係なく、後続のすべての部分をそれらの列に同じ順序で入力します。

したがって、2 番目の部分の 5 番目と 6 番目の列 (エイリアスA3DuplexPagesPrintedand を指定) は、結果の 5 番目と 6 番目の列に入力され、 and (最初の SELECT 句のエイリアス)A3DuplexTotalCostと名付けられます。A3PagesPrintedA3TotalCost

2 つのクエリの列を区別する場合は、クエリの各部分にすべての列を指定する必要があります (以下の 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 に答える