2016-08-15 46 views
1

數據庫:任何人都可以幫我約SQL查詢(羣裏)

訂單:

| orders_id | shop_id |mode| 
|:-----------|------------:|---:| 
| 1   |  1001 | 1| 
| 2   |  1001 | 1| 
| 3   |  1001 | 2| 
| 4   |  1003 | 1| 
| 5   |  1004 | 1| 
| 6   |  1004 | 2| 

顯示:總= total_mode_1 * 20 + total_mode_2 * 10;

| shop_id |total Mode 1|total Mode 2|total| 
|:-----------|-----------:|-----------:|----:| 
| 1001  |   2|   1| 50| 
| 1004  |   1|   1| 30| 
| 1003  |   1|   0| 20| 

我有數據結構。你可以查詢這個嗎?我嘗試了一些時間,但沒有工作。 非常感謝!基於

回答

1

這是根據您所提供的公式查詢,

select shop_id, 
    count(case when o_mode = 1 then 1 end) as tm_1, 
    count(case when o_mode = 2 then 1 end) as tm_2, 
    count(case when o_mode = 1 then 1 end)*20 + count(case when o_mode = 2 then 1 end)*10 as total 
from order_test 
group by shop_id 
order by total desc; 

結果:

+---------+------+------+-------+ 
| shop_id | tm_1 | tm_2 | total | 
+---------+------+------+-------+ 
| 1001 | 2 | 1 | 50 | 
| 1004 | 1 | 1 | 30 | 
| 1003 | 1 | 0 | 20 | 
+---------+------+------+-------+ 
3 rows in set (0.00 sec) 

您可以在order by條款適用ascdesc,根據您的需要。很顯然,查詢存在冗餘。但我認爲我們不能擺脫它,因爲更名列不能在select中使用。

注意:o_mode = mode。我剛更名了專欄。

+0

謝謝你的男人。它對我有用:) – Phongdatgl

3

在MySQL更容易,當你使用局部變量:

SELECT 
    shop_id, 
    SUM(@tm1 := IF(`mode`=1, 1, 0)) AS tot_mode_1, 
    SUM(@tm2 := IF(`mode`=2, 1, 0)) AS tot_mode_2, 
    SUM(@tm1 * 20 + @tm2 * 10) AS total 
FROM orders 
GROUP BY shop_id 
ORDER BY total desc 

我們做的是檢查,如果模式是1個或2,店裏局部變量的每一行,這個局部變量,我們以後需要算總

結果將是:

shop_id  tot_mode_1 tot_mode_2 total 
1001  2   1   50 
1004  1   1   30 
1003  1   0   20 
相關問題