2014-08-30 28 views
0

我正在嘗試編寫查詢來查找出現在我的數據集中的新訂單項。所以例如我有以下表結構。用於識別當前月份的新訂單項的邏輯

邏輯需要確定如果行項目是新的,因爲以前的billedmonth

表A

Table Structure

所以,如果我把它寫在英語。

選擇IF「CLI」 &「說明」 &「UnitCost」不存在BilledMonth -1

我已成功創建,如果它存在以前的結算月份聯接顯示。

但我真的負邏輯掙扎(即線項目是新本月)

任何幫助極大的讚賞。

回答

0
SELECT t.CLI, t.Description 
FROM yourTable t 
LEFT JOIN yourTable t2 
ON t.CLI = t2.CLI 
AND t.Description = t2.Description 
AND t.UnitCost = t2.UnitCost 
AND t.BilledMonth - 1 = t2.BilledMonth 
WHERE t2.CLI is null 
+0

使用其中一個連接列進行空檢查 – 2014-08-30 07:47:05

+0

就是這樣,所以額外的評論確實不是強制性的,謝謝! – Ndech 2014-08-30 07:50:45

0

我認爲SQL Server的支持分析功能,所以這樣的事情應該工作:

select CLI, Description, UnitCost, billedMonth 
from (
    select CLI, Description, UnitCost, billedMonth 
     count(*) over (partition by CLI, Description, UnitCost order by billedMonth) cnt 
    from mytable 
) where cnt = 1 

當且僅當這個作品很可能是方式更有效,更比加入基於select語句更快。