2016-07-25 73 views
0

給定2個表,我想從[Purchase]表中生成前3個最高金額。 附加條件是[Crocs]必須包含在記錄的前3位。MySQL包含一個特定的行,其順序爲

我有以下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(卡駱馳)總量

+0

爲什麼結果B是51? – Blank

+0

你有一個從B類,但你沒有領域上.. –

回答

0

從scaisEdge的答案几乎是正確的,但第一個查詢還可以與鱷魚返回一行s並且排序錯誤(按最大(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 
+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' 
0

試試這個:

SELECT sum(amount)as sum_amount,a.store_id,storename,category from 
(select amount,store_id from tbl_purchase) as a 

inner JOIN 

(select store_id,storename,category from tbl_store)as b on a.store_id = b.store_id where b.category = 'supermarket' GROUP BY category