mysql - 仅返回最大值大于指定值的行

标签 mysql sql max

嗨,我在这里问了一个问题: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/

相关文章:

sql - 在 Oracle SQL 中将用户提示作为日期(甚至是字符串)传递

sql - PostgreSQL - 如何动态转换?

sql - PostgreSQL : Check if the last number is the highest

mysql - SQL中如何从COUNT中选择MAX

mysql - SQL查询以获取重复字段的最大数量

MySQL创建存储过程语法错误问题

mysql - 使用算术运算优化MySQL嵌套select

c# - 创建新的数据库并填充另一个数据库

r - 如何返回一列的行值,使得它们在另一列中的对应值是R中最小的n值

mysql - 无法通过分区来改变查询时间