我有这个代码,它显示了上个月提供服务的品牌
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月份插入一个新行。我想要发生的是因为我在Polo上服务然后它不再出现在列表中,列表应该是
Brand | ID | Last Serviced
Shirt | 2 | 12/24/2013
我是怎么做到的?我还要添加什么?
答案 0 :(得分: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;
答案 1 :(得分: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