如何为这个scenerio编写SQL查询?

时间:2017-06-16 18:32:59

标签: sql-server matching records

我正在尝试编写一个查询,其中我想要table2中table2中满足下面第一个内部连接条件的所有项目(这是工作查找)。

然后我想检查table3是否有异常。例外情况基于参考编号(REF_NO)。如果参考编号存在于表3中,那么我需要检查商店编号(STORE_NO)是否匹配。如果它们匹配,那么我想要table1中的匹配记录。如果没有,则从table1中排除匹配的记录。

但是,如果表3中没有参考号,那么我希望table1中的记录与table2匹配。

由于

USE master
GO

table1
table2
table3

SELECT
   T1.TERMINAL,
   T1.OPERATOR,
   T1.TRANS_NO,
   T1.SEQ_NO,
   T1.STORE_NO,
   T2.REF_NO,
   T2.SDATE,
   T2.EDATE,
   T1.POS_DATE,
   T1.ITEM,
   T1.ITYPE,
   T1.SOLD_QTY,
   T1.PRICE,
   T2.OI_AMT
FROM [table1] As T1

INNER JOIN [table2] As T2
ON (T1.ITEM = T2.ITEM)  And (T1.POS_DATE BETWEEN T2.SDATE And T2.EDATE)

INNER JOIN [table3] As T3
ON (T2.REF_NO = T3.REF_NO) And (T1.STORE_NO = T3.STORE)

1 个答案:

答案 0 :(得分:0)

SELECT
   T1.TERMINAL,
   T1.OPERATOR,
   T1.TRANS_NO,
   T1.SEQ_NO,
   T1.STORE_NO,
   T2.REF_NO,
   T2.SDATE,
   T2.EDATE,
   T1.POS_DATE,
   T1.ITEM,
   T1.ITYPE,
   T1.SOLD_QTY,
   T1.PRICE,
   T2.OI_AMT
FROM [table1] As T1
INNER JOIN [table2] As T2
    ON T1.ITEM = T2.ITEM
    AND T1.POS_DATE > T2.SDATE 
    AND T1.POS_DATE <= T2.EDATE
WHERE EXISTS (  SELECT TOP (1) 1
                FROM table3 as T31
                WHERE T2.REF_NO = T31.REF_NO
                AND T1.STORE_NO = T31.STORE)
OR NOT EXISTS ( SELECT TOP (1) 1
                FROM table3 as T32
                WHERE T2.REF_NO = T32.REF_NO)

这应该有效,它会检查你的两个条件。我还建议您不要使用BETWEEN子句并使用两个条件指定日期范围。