0

table1table2およびtable3異なる列がありますが、すべてに列がありOrderDateます。3 つのテーブルすべてから行の結果セットを取得し、最終的な結果セットを で並べ替えたいと考えていOrderDateます。

( select * from table1 LEFT  join table2 on 0=1 LEFT  join table3 on 0=1
     where somedate <= table1.orderdate ) 

union all

( select * from table1 RIGHT join table2 on 0=1 LEFT  join table3 on 0=1   
     where somedate <= table2.orderdate ) 

union all

( select * from table1 RIGHT join table2 on 0=1 RIGHT join table3 on 0=1
    where somedate <= table3.orderdate )

これは機能しますが、この結果セットを次の順序で並べたいorderdateので、次を追加します。

order by case when table1.orderdate is not null then table1.orderdate
              when table2.orderdate is not null then table2.orderdate
              else table3.orderdate end

SQL Server は、「ステートメントに UNION、INTERSECT、または EXCEPT 演算子が含まれている場合、ORDER BY 項目を選択リストに含める必要があります」というエラーを返します。

交換したら

select *

select *, table1.orderdate, table2.orderdate, table3.orderdate

同じエラーが発生します。

は?ありがとう。

4

2 に答える 2

1

これを試して

Select * from 
(( select * from table1 LEFT  join table2 on 0=1 LEFT  join table3
     where somedate <= table1.orderdate ) 

union all

( select * from table1 RIGHT join table2 on 0=1 LEFT  join table3    
     where somedate <= table2.orderdate ) 

union all

( select * from table1 RIGHT join table2 on 0=1 RIGHT join table3
    where somedate <= table3.orderdate )) A

Order by A.orderdate
于 2012-05-20T05:03:33.310 に答える
0

共通テーブル式を使用して問題を解決しました。これが私がしたことです:

WITH JoinedTable as
(
    ( select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
      from table1 LEFT  join table2 on 0=1 LEFT  join table3 on 0=1
      where somedate <= table1.orderdate ) 

    union all

    ( select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
      from table1 RIGHT join table2 on 0=1 LEFT  join table3 on 0=1   
      where somedate <= table2.orderdate ) 

    union all

    ( select table1.col1 as t1col1, table2.col2 as t1col2 [etc...] 
      from table1 RIGHT join table2 on 0=1 RIGHT join table3 on 0=1
      where somedate <= table3.orderdate )
)

select *, case when t1orderdate is not null then t1orderdate
               when t2orderdate is not null then t2orderdate
               else t3orderdate end
               AS DateForOrderingResultSet
from JoinedTable order by DateForOrderingResultSet

table1.col1 as t1col1, table2.col2 as t1col2 [etc...]

、 、が同一の列名 (たとえば) を持っている場合、どちらを置き換える*かは避けられません。そうでない場合、SQL Serverはあいまいであるというエラーをスローします。これがまたはまたはを意味するかどうかを知る方法がありません。table1table2table3IDJoinedTable.IDtable1.IDtable2.IDtable3.ID

于 2012-05-20T20:16:37.397 に答える