2012-08-05 151 views
0

我有一個查詢將檢查表中的無效發票,然後檢查同一張表 以查看無效發票是否重新提交。我想知道的是...有沒有方法 添加一列以查看如果無效發票不重新招標,並在列中列爲「N」..在數據庫中列出匹配的記錄和不匹配的記錄

這裏是我當前的查詢:

SELECT  t1.Store_Number, t1.Invoice_Number, t1.Invoice_Date, t1.Vehicle_Tag, t1.Void_Reason, t1.Void_Employee_Tax_Payer_Id, t1.Invoice_Total, t1.Void_Flag, 
         t2.Invoice_Number AS Expr1, t2.Vehicle_Tag AS Expr2, t2.Invoice_Total AS Expr3 
FROM   Invoice_Tb AS t1 INNER JOIN 
         Invoice_Tb AS t2 ON t1.Vehicle_Tag = t2.Vehicle_Tag 
WHERE  (t1.Void_Flag = 'y') AND (t1.Invoice_Date BETWEEN CONVERT(DATETIME, '2012-08-01 00:00:00', 102) AND CONVERT(DATETIME, '2012-08-02 00:00:00', 102)) AND 
         (t2.Void_Flag = 'n') AND (t2.Invoice_Date BETWEEN CONVERT(DATETIME, '2012-08-01 00:00:00', 102) AND CONVERT(DATETIME, '2012-08-02 00:00:00', 102)) 

這裏是我的電流輸出:

Store Number Invoice Number Date Plate Number Void Reason Employee Invoice Amount Voided New Invoice Number Plate Number New Invoice Amount Re-Tendered 
1568 3257714 8/1/2012 0:00 BBY1234 WRONG PRICE ENTERED 89556532 21.39 3257714 BBY1234 26.74 Y 

的我想什麼例子:比方說,發票#123失效,從來沒有重新招標......我想要 顯示上面的內容並添加一個列標題「重新標記」並列出「n」,其中一個invo冰不是 重新招標。輸出將類似於此:

Store Number Invoice Number Date Plate Number Void Reason Employee Invoice Amount Voided New Invoice Number Plate Number New Invoice Amount Re-Tendered 
1568 3257714 8/1/2012 0:00 BBY1234 WRONG PRICE ENTERED 89556532 21.39 3257714 BBY1234 26.74 Y 
1552 123 8/1/2012 0:00 Dwb0534 Wrong Plate number 73215654 15.95    N 

回答

1

你需要一個左連接

SELECT  t1.Store_Number, t1.Invoice_Number, t1.Invoice_Date, t1.Vehicle_Tag, t1.Void_Reason, t1.Void_Employee_Tax_Payer_Id, t1.Invoice_Total, t1.Void_Flag, 
         t2.Invoice_Number AS Expr1, t2.Vehicle_Tag AS Expr2, t2.Invoice_Total AS Expr3, case when t2.Vehicle_Tag is null then 'n' else 'y' end as retendered 
FROM   Invoice_Tb AS t1 LEFT JOIN 
         Invoice_Tb AS t2 ON t1.Vehicle_Tag = t2.Vehicle_Tag And 
         (t2.Void_Flag = 'n') AND (t2.Invoice_Date BETWEEN CONVERT(DATETIME, '2012-08-01 00:00:00', 102) AND CONVERT(DATETIME, '2012-08-02 00:00:00', 102)) 
WHERE  (t1.Void_Flag = 'y') AND (t1.Invoice_Date BETWEEN CONVERT(DATETIME, '2012-08-01 00:00:00', 102) AND CONVERT(DATETIME, '2012-08-02 00:00:00', 102)) 
+0

它不喜歡的第一個「和」左後加入。 – Shmewnix 2012-08-05 17:00:35

+0

@Shmewnix,哎呀,擺脫了尾隨和 – iruvar 2012-08-05 17:04:19

+0

剛剛找到它。太棒了!謝謝! – Shmewnix 2012-08-05 17:04:53