带有WHERE CLAUSE的MYSQL GROUP BY

时间:2018-01-17 17:51:17

标签: mysql greatest-n-per-group

我查看过最大的n-group-by组,找不到这个答案,也无法使JOIN解决方案与WHERE CLAUSE一起使用。这就是我所拥有的。

t1表:

ID  Product_Name    Quantity    pharmacyShort   Copay_Amount
581284  AMLODIPINE 10 MG    30  WALGREENS   21.07
581283  AMLODIPINE 10 MG    30  CVS 36.61
581282  AMLODIPINE 10 MG    28  RITE AID    30.98
581280  AMLODIPINE 10 MG    60  WALGREENS   50.65
581279  AMLODIPINE 10 MG    30  CVS 29.78
581278  AMLODIPINE 10 MG    30  RITE AID    14.28
581277  AMLODIPINE 10 MG    180 WALGREENS   33.83
581276  AMLODIPINE 10 MG    15  CVS 18.33
581275  AMLODIPINE 10 MG    10  RITE AID    45.93
581274  AMLODIPINE 10 MG    30  PUBLIX  33.75

我还有一个优先级表,称之为t2,我希望输出优先级(排序):

id  pharmacyShort   COUNT
1   CVS 100
2   RITE AID    99
3   TARGET  98
4   WALGREENS   97
5   WALMART 96
6   KMART   95
7   KROGER  94
8   PUBLIX  93

MYSQL:

SELECT t1.pharmacyShort , t1.Copay_Amount 
FROM `t1` 
INNER JOIN `t2` 
ON t1.pharmacyShort = t2.pharmacyShort 
WHERE t1.Product_Name = 'AMLODIPINE 10 MG' 
AND t1.Quantity = '30' 
AND t1.ID > 555000 
GROUP BY t1.pharmacyShort 
ORDER BY t2.COUNT DESC LIMIT 30

我有ID> 555000保持查询时间低。此外,我试图显示最近的价格。也许这可以通过ORDER BY来完成,但挑战在于,有些药物有更多的要求,而有些药物则要少得多,这意味着我必须回到过去才能获得价格。

我希望得到的是这个(我实际上只需要输出上的pharmacyShort和Copay_Amount列,但为了清楚起见,请保留其他列):

581283  AMLODIPINE 10 MG    30  CVS 36.61
581284  AMLODIPINE 10 MG    30  WALGREENS   21.07
581278  AMLODIPINE 10 MG    30  RITE AID    14.28
581274  AMLODIPINE 10 MG    30  PUBLIX  33.75

输出应该只选择ID为581283的CVS,并且只显示来自CVS的一个声明,而是(正如我所知)GROUP BY正在选择旧声明581279,如下所示:

581279  AMLODIPINE 10 MG    30  CVS 29.78
581284  AMLODIPINE 10 MG    30  WALGREENS   21.07
581278  AMLODIPINE 10 MG    30  RITE AID    14.28
581274  AMLODIPINE 10 MG    30  PUBLIX  33.75

如果它更容易,我可以没有优先级表。我也考虑过通过某种数组排序来尝试在PHP方面解决这个问题,但我认为MYSQL会更快。

许多,非常感谢和任何可以帮助的所有人的业力。

更新

根据我得到的答案,我就在这里:

SELECT a.pharmacyShort, a.copay_amount
FROM `t1` a
JOIN (SELECT MAX(ID) as maxid, pharmacyShort
FROM `t1`
WHERE Product_Name = 'AMLODIPINE 10 MG' 
      AND Quantity = '30' 
      GROUP BY pharmacyShort) AS maxt1
  ON a.pharmacyShort = maxt1.pharmacyShort AND a.id = maxt1.maxid
join t2 b ON a.pharmacyShort = b.pharmacyShort
ORDER BY b.count DESC
LIMIT 20

我从WHERE子句中删除了id> 550000因为使用MAX(ID)我认为我不需要它。

但我得到的结果为零。那么我哪里出错?

1 个答案:

答案 0 :(得分:0)

SQL select only rows with max value on a column使用加入简单组标识符,最大值组内子查询方法,并将条件放在子查询中。

然后将其加入t2以获取count列进行排序。

SELECT t1.pharmacyShort, t1.copay_amount
FROM t1
JOIN (SELECT pharmacyShort, MAX(id) AS maxid
      FROM t1
      WHERE Product_Name = 'AMLODIPINE 10 MG' 
      AND Quantity = '30' 
      AND ID > 555000
      GROUP BY pharmacyShort) AS maxt1
    ON t1.pharmacyShort = maxt1.pharmacyShort AND t1.id = maxt1.maxid
JOIN t2 on t1.pharmacyShort = t2.pharmacyShort
ORDER BY t2.count DESC
LIMIT 20