嗨,我在这里问了一个问题:Return only rows whose max value is less than specified
我得到的答案非常符合我的要求:
SELECT *
FROM tbldealermobiles
INNER JOIN tblhistory ON tbldealermobiles.FCS = tblhistory.FCS
INNER JOIN tblAllDealers ON tbldealermobiles.FCS = tblAllDealers.FCS
WHERE tblAllDealers.CustGroup in ('Virtual', 'Outbound')
GROUP BY tbldealermobiles.mobilenumber
HAVING MAX(tblhistory.PurchaseDate) <
MAX(case when tblAllDealers.CustGroup = 'Virtual' then date('2013-03-22')
when tblAllDealers.CustGroup = 'Outbound' then date('2013-04-21')
end)
ORDER BY tblhistory.PurchaseDate DESC
我试图通过简单地将小于符号更改为大于符号来重新调整它的用途,如下所示:
SELECT *
FROM tbldealermobiles
INNER JOIN tblhistory ON tbldealermobiles.FCS = tblhistory.FCS
INNER JOIN tblAllDealers ON tbldealermobiles.FCS = tblAllDealers.FCS
WHERE tblAllDealers.CustGroup in ('Virtual', 'Outbound')
GROUP BY tbldealermobiles.mobilenumber
HAVING MAX(tblhistory.PurchaseDate) >
MAX(case when tblAllDealers.CustGroup = 'Virtual' then date('2013-03-22')
when tblAllDealers.CustGroup = 'Outbound' then date('2013-04-21')
end)
ORDER BY tblhistory.PurchaseDate DESC
但是我得到了指定日期之前的手机号码,这个查询可以这样使用还是需要重写?
输出:
我得到 795 行,这是最后 15 行:
PurchaseDate CustGroup
2012-05-12 Outbound
2012-05-12 Outbound
2012-05-11 Virtual
2012-05-10 Virtual
2012-05-10 Outbound
2012-05-10 Outbound
2012-05-10 Virtual
2012-05-10 Outbound
2012-05-10 Outbound
2012-05-10 Virtual
2012-05-09 Outbound
2012-05-09 Outbound
2012-05-09 Outbound
2012-05-08 Outbound
2012-05-08 Outbound
提前致谢。
最佳答案
我会像这样完成您的原始查询..
select *
FROM tbldealermobiles m
INNER JOIN tblhistory h ON m.FCS = h.FCS
INNER JOIN tblAllDealers a ON m.FCS = a.FCS
WHERE a.CustGroup in ('Virtual', 'Outbound')
and h.PurchaseDate = (
select max(h2.PurchaseDate) from tblhistory h2
where h2.fcs = a.fcs)
and (a.CustGroup = 'Virtual' AND
h.PurchaseDate < date('2013-03-22')
or
a.CustGroup = 'Outbound' AND
h.PurchaseDate < date('2013-04-21'))
ORDER BY h.PurchaseDate DESC
然后,对于此查询,只需更改 <
符号为 >
.
关于mysql - 仅返回最大值大于指定值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16690917/