簡體   English   中英

需要有關SQL查詢的幫助

[英]Need help with SQL query

我有兩個結構如下的表:

表一

id title   date
1  testing1 2001-05
1  testing2 2003-05

表b

id code   date
1  aaaa 2001-01
1  bbbb 2003-01

當我連接這兩個表時,我得到三行,但我只想要2行?

(query)
select distinct a.*, b.*
from table a, table b
where a.date in ('2001-05','2003-05')
and a.id=b.id
and b.date < a.date  ---> I know the error is coming from here.

錯誤的輸出看起來像這樣

id title   date     id   code   date
1  testing1 2001-05 1    aaaa   2001-01
1  testing1 2003-05 1    aaaa   2003-01-------this is duplicated because the date is in fact less than, 
1  testing2 2003-05 1    bbbb   2003-01

正確的輸出應該是:

id title   date     id   code   date
1  testing1 2001-05 1    aaaa   2001-01
1  testing2 2003-05 1    bbbb   2003-01

您可能希望ID:是唯一的。 將主鍵添加到ID列。

Select A.id, A.title, A.date
    , B.id, B.code, B.date
From TableA As A
    Join    (
            Select A.id, A.title, A.date
                , Min( B.Date ) As BDate
            From TableA As A
                Left Join TableB As B
                    On B.id = A.id
                        And B.Date < A.Date
            Where A.Date In('2001-05-01','2003-05-01')
            Group By A.id, A.title, A.date
            ) As Z
        On Z.id = A.id
            And Z.title = A.title
            And Z.date = A.date
    Join TableB As B
        On B.id = A.id
            And B.date = Z.BDate

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM