MySQL包含一个具有order by的特定行

时间:2016-07-25 06:34:54

标签: mysql sql

鉴于2个表,我想从[Purchase]表中生成前3个最高金额。 其他标准是[Crocs]必须包含在记录的前3位。

我有以下SQL,但它无法生成我想要的结果(结果A),请指导我如何在结果B中取出结果。谢谢。

表(购买):

Purchase_ID | StoreID | Amount
------------|---------|--------
  1         |  21     |   22
  2         |  23     |   13
  3         |  25     |   6
  4         |  26     |   23
  5         |  28     |   18

表(商店):

Store_ID | StoreName     
---------|----------
  21     |  Adidas
  22     |  Nike
  23     |  Puma
  24     |  New Balance
  25     |  Crocs
  26     |  Converse

SQL:

SELECT IF(SUM(amount) IS NULL, 0, SUM(amount)) as totalAmount
FROM (
    SELECT a.amount
    FROM purchase a
    INNER JOIN store b
    ON a.store_id = b.storeid
    GROUP BY a.amount
    HAVING b.StoreName = 'Crocs'
    ORDER BY a.amount DESC
    LIMIT 3
) t

结果A:$ 6

解释A:Crocs的金额为$ 6

结果B:51美元

解释B:前3名的总金额= 22美元(阿迪达斯)+ 23(美洲狮)+ 6美元(Crocs)

3 个答案:

答案 0 :(得分:0)

你可以使用联盟

  SELECT b.storename, max(a.amount)
  FROM purchase a
  INNER JOIN store b
  ON a.store_id = b.storeid
  GROUP BY a.storename
  order by max(a.amount) limit 2
  union 
  SELECT b.storename, a.amount
  FROM purchase a
  INNER JOIN store b
  ON a.store_id = b.storeid
  where b.storename='crocks'

答案 1 :(得分:0)

试试这个:

https://

答案 2 :(得分:0)

scaisEdge的答案几乎是正确的,但是第一个查询也可能返回一行带有crocs并且排序错误(按max(a.amount)限制2的顺序意味着将显示最低的2个结果)。此外,您可以将查询包装在另一个选择查询中以对结果进行排序

  SELECT * FROM (
    SELECT b.storename, max(a.amount) as maxAmount
      FROM purchase a
      INNER JOIN store b ON a.store_id = b.storeid
      WHERE b.storename != 'crocks'
      GROUP BY a.storename
      ORDER BY max(a.amount) DESC 
      LIMIT 2
    UNION 
      SELECT b.storename, a.amount as maxAmount
      FROM purchase a
      INNER JOIN store b
      ON a.store_id = b.storeid
      WHERE b.storename='crocks'
      ORDER BY a.amount DESC
      LIMIT 1
  ) ORDER BY maxAmount DESC 
相关问题