如何使用SQL检查一个客户的多行?

时间:2017-04-18 15:24:47

标签: sql sql-server

我有一张这样的表:

id | START_DATE | END_DATE   | id_customer
----------------------------------------
1  | 01/05/2016 | 31/05/2016 | 1234
2  | 10/10/2016 | 11/11/2016 | 1234
3  | 11/11/2016 | 15/05/2017 | 1234
4  | 31/12/2016 | 31/06/2017 | 1234

如果START_DATE等于END_DATE,我想要选择。

例如:

11/11/2016 line id 3不等于31/05/2016 line id 1

11/11/2016 line id 3 equal 11/11/2016 line id 2

11/11/2016 line id 3不等于15/05/2017 line id 3

11/11/2016 line id 3不等于31/06/2017 line id 4

我已尝试过像这样的请求

SELECT id_cutsomer,START_DATE, END_DATE
FROM TABLE
WHERE START_DATE IN (
    SELECT END_DATE FROM DATA_BEAUTY_BOX
)

我想要这个结果:

 START_DATE | END_DATE   | id_customer
------------------------------------
 11/11/2016 | 11/11/2016 | 1234

你能帮助我吗?

提前致谢

2 个答案:

答案 0 :(得分:3)

我认为自我join应该足够了

select  t1.START_DATE, t2.END_DATE, t1.ID_CUSTOMER
from    yourTable t1
join    yourTable t2
on      t1.START_DATE = t2.END_DATE

如果您不想混合不同客户的日期,则必须使join条件更严格

select  t1.START_DATE, t2.END_DATE, t1.ID_CUSTOMER
from    yourTable t1
join    yourTable t2
on      t1.START_DATE = t2.END_DATE and
        t1.ID_CUSTOMER = t2.ID_CUSTOMER

答案 1 :(得分:0)

我会在客户ID上加入表格,然后在WHERE子句上添加(开始日期=结束日期)条件。 (虽然你可以在JOIN上做到这两点)

SELECT t1.START_DATE, t2.END_Date, t1.id_customer 
FROM MyTable t1     
    INNER JOIN MyTable t2   
        ON t1.id_customer = t2.id_customer
WHERE t1.START_DATE = t2.END_Date