2016-05-12 66 views
0

嗯,這個標題可能令人困惑,所以讓我試着通過顯示一些表和查詢來解釋我的問題。我有一個表「_commision」包含在其他之中以下行:MySQL:根據兩個不同的ENUM值從不同行中選擇最小值和最大值

+-------+-------------+------+----------------+----------------+-----------+ 
| id | relation_id | type | min_commission | max_commission | percental | 
+-------+-------------+------+----------------+----------------+-----------+ 
| 22892 |  3427 | SALE |   1.40 |   1.80 | yes  | 
| 22891 |  3427 | SALE |   30.00 |   60.00 | no  | 
| 21075 |  6365 | LEAD |   30.00 |   NULL | no  | 
| 19638 |  4436 | SALE |   1.10 |   NULL | yes  | 
| 19637 |  4436 | LEAD |   30.00 |   NULL | no  | 
+-------+-------------+------+----------------+----------------+-----------+ 
5 rows in set (0.00 sec) 

我需要得到絕對min_commission價值和絕對價值max_commission。棘手的部分是百分比列,你會在後面看到。我的第一個想法是這樣的:

SELECT rc.type, rc.currency_id, rc.percental, 
    MIN(rc.min_commission) AS min_commission, 
    IF(MAX(GREATEST(rc.min_commission, rc.max_commission)) > MIN(rc.min_commission) , MAX(GREATEST(rc.min_commission, rc.max_commission)) , 0.00) AS max_commission 
FROM _commission rc 
LEFT JOIN ... 
GROUP BY rc.type; 

此查詢結果如下行:

+------+-------------+-----------+----------------+----------------+ 
| type | currency_id | percental | min_commission | max_commission | 
+------+-------------+-----------+----------------+----------------+ 
| LEAD |   1 | no  |   30.00 |   0.00 | 
| SALE |   1 | no  |   1.10 |   60.00 | 
+------+-------------+-----------+----------------+----------------+ 
2 rows in set (0.00 sec) 

不過,我需要得到一個結果,認爲該列「percental」,因爲如果該類型是'SALE',佣金可以是1.4%,例如30美元(百分比或修復)。正如你所看到的,我需要像下面這樣的結果,但是我無法得到合適的查詢。這是如何結果應該是這樣的:

+------+-------------+-----------+----------------+----------------+ 
| type | currency_id | percental | min_commission | max_commission | 
+------+-------------+-----------+----------------+----------------+ 
| LEAD |   1 | no  |   30.00 |   0.00 | 
| SALE |   1 | yes  |   1.10 |   1.80 | 
| SALE |   1 | no  |   30.00 |   60.00 | 
+------+-------------+-----------+----------------+----------------+ 

任何想法?

回答

1

試試這個,

SELECT 
      rc.type, rc.currency_id, rc.percental, 
      MIN(rc.min_commission) AS min_commission, 
      IF(MAX(GREATEST(rc.min_commission, rc.max_commission)) 
      > 
      MIN(rc.min_commission) , MAX(GREATEST(rc.min_commission, rc.max_commission)) , 0.00) AS max_commission 
    FROM 
      _commission rc 
    LEFT JOIN ... 
    GROUP BY 
      rc.type, rc.percental; 
+0

UFFF ....哈哈哈!對我感到羞恥:D我看不到樹木。需要睡覺 - 或咖啡。感謝Hytool!哈哈哈.... – Dong3000

相關問題