0

データ:

表1:

ID          Value1          Date1
 1          foo             2013-04-27
 2          bar             2013-05-01
 3          umm             2013-05-29
 4          ba              2013-06-09
 5          sne             2013-04-30
 6          xyz             2013-07-11
 7          aosid           2013-07-08

リンクテーブル:

link        MainID          SubID
 A          1               3
 B          3               1
 A          1               4
 B          4               1
 A          2               6
 B          6               2

クエリ:

select t1.ID, t1.Value1, t1.Date1 
from Table1 t1 
where t1.Date1 between '2013-04-24' and '2013-05-08'

union

select t2.ID, t2.Value1, t2.Date1 
from Table1 t2 
where t2.ID in (select LT.SubID 
                from LinkTable LT 
                where LT.link = 'A' and LT.MainID = t1.ID)

これは私が試したもので、t1.ID をバインドできないというエラーが表示されます。これは、最初の選択のデータを 2 番目の選択で使用できないことを意味します。

最初の選択の ID 値を 2 番目の選択で使用する方法はありますか?

ご助力いただきありがとうございます。

望ましい結果:

ID        Value1        Date1
 1        foo           2013-04-27
 3        umm           2013-05-29
 4        ba            2013-06-09
 2        bar           2013-05-01
 6        xyz           2013-07-11
 5        sne           2013-04-30

したがって、結果をもう少しよく説明するには、最初の選択に日付範囲内のすべてのレコードを含める必要があります。2 番目の選択では、LinkTable を介して最初の選択から含まれるレコードの 1 つにリンクされているかどうかを確認します。

4

2 に答える 2

2

CTEがあなたのロジックを助けてくれると思います。

あなたの説明に基づいて、私は組合なしでこのアプローチを思いつきました:

with ids as (
      select t1.*
      from table1 t1
      where t1.Date1 between '2013-04-24' and '2013-05-08' 
     )
select t1.*
from table1 t1 left outer join
     linktable lt
     on t1.id = lt.subid and
        lt.mainid in (select id from ids) 
where lt.mainid is not null or
      t1.Date1 between '2013-04-24' and '2013-05-08' 

ユニオンとして書き換えることもできます:

with ids as (
      select t1.*
      from table1 t1
      where t1.Date1 between '2013-04-24' and '2013-05-08' 
     )
select t.*
from ((select * from ids)
      union
      (select *
       from table1 t1 join
            linktable lt
            on t1.id = lt.subid
       where lt.mainid in (select id from ids)
      )
     ) t
于 2013-05-15T13:50:38.630 に答える
0

いいえ、ユニオン サブクエリは互いに独立しています。これを使用してクエリをすばやく変更できます(最適なものについては考えていません。自分のクエリを変更しただけです)。

select t1.ID, t1.Value1, t1.Date1 
from Table1 t1 
where t1.Date1 between '2013-04-24' and '2013-05-08'

union

select t2.ID, t2.Value1, t2.Date1 
from Table1 t2 
where t2.ID in (select LT.SubID 
            from LinkTable LT 
            left join Table1 t1 on LT.MainID = t1.ID
            where LT.link = 'A' and t1.Date1 between '2013-04-24' and '2013-05-08')
于 2013-05-15T13:47:10.480 に答える