2014-01-22 56 views
0

我有這樣的代碼服務品牌它表明,在上月所服務的品牌如何才能不顯示,在過去的一個月

SELECT t1.Brand, t1.ID, 

DATE_FORMAT((t2.Tstamp), "%m/%e/%Y") AS "Last Serviced", 


FROM Table1 t1 

INNER JOIN Table2 t2 
ON t1.ID = t2.Equip_ID 

WHERE 
MONTH(t2.Tstamp) <> "01" 
Group by t1.ID 
Order by t2.Tstamp 

的輸出存在

Brand | ID | Last Serviced 
Polo | 1 | 12/12/2013 
Shirt | 2 | 12/24/2013 

然後,如果我這樣做該品牌的另一項服務是Polo,它將在1月份插入一個新的行。我希望發生的,因爲我在波羅做服務,那麼它不會出現在列表中了,名單應該是

Brand | ID | Last Serviced 
Shirt | 2 | 12/24/2013 

我如何呢?我還添加了什麼?

回答

1

您想要最近的服務日期爲上個月的品牌。爲此,使用having

SELECT t1.Brand, t1.ID, DATE_FORMAT(t2.Tstamp, "%m/%e/%Y") AS "Last Serviced", 
FROM Table1 t1 INNER JOIN 
    Table2 t2 
    ON t1.ID = t2.Equip_ID 
Group by t1.ID 
having MONTH(max(t2.Tstamp)) <> "01" 
Order by t2.Tstamp; 

我將包括在比較的年份和月份,但這種跟隨你的原始查詢的邏輯。

編輯:

要包括今年在查詢中,立足於當前日期的比較:

SELECT t1.Brand, t1.ID, DATE_FORMAT(t2.Tstamp, "%m/%e/%Y") AS "Last Serviced", 
FROM Table1 t1 INNER JOIN 
    Table2 t2 
    ON t1.ID = t2.Equip_ID 
Group by t1.ID 
having year(max(t2.Tstamp)) <> year(now()) and 
     month(max(t2.Tstamp)) <> month(now()) 
Order by t2.Tstamp; 
+0

知道了!謝謝Youuuu! – sleepsleepsleep90731

+0

如何將月份和年份包含在比較中,就像你說的一樣? – sleepsleepsleep90731

+0

太好了,謝謝! :) – sleepsleepsleep90731

1

使用CASE語句。讓我們看看:

SELECT t1.Brand, t1.ID, 
case(when MONTH(t2.Tstamp)=01 then NULL else DATE_FORMAT(t2.Tstamp, "%m/%e/%Y") end) as `Last Serviced` 
from FROM Table1 t1 INNER JOIN Table2 t2 ON t1.ID = t2.Equip_ID 
Group by 2 Order by 3 
相關問題