2017-02-16 67 views
1

選擇多行我有MYSQL表命名爲permit_bills其中包含爲bill_noalcohol_typorigin2000ml1000mlbill_date列。表如下所示:MYSQL - 在單行

+---------+--------------+---------+--------+--------+-----------+ 
    | bill_no | alcohol_typ | origin | 2000ml | 1000ml | bill_date | 
    +---------+------------- + --------+--------+--------+-----------+ 
    | 2001 | s   | f  | 2 | 1 |01-02-2017 | 
    | 2001 | m   | w  | 3 | 4 |01-02-2017 | 
    +---------+--------------+---------+--------+--------+-----------+ 

我希望用他們bill_nobill_date選擇從上面表中的所有行到單個行和要顯示的2000ml1000ml列按他們alcohol_typ和`原點。

我的產出表必須是這樣的:

+---------+--------------+-------------+------------+------------+-----------+ 
    | bill_no | s_f_2000ml | s_f_1000ml | m_w_2000ml | m_w_1000ml | bill_date | 
    +---------+------------- + ------------+------------+------------+-----------+ 
    | 2001 |  2  |  1  |  3  |  4  |01-02-2017 | 
    +---------+--------------+-------------+------------+------------+-----------+ 
+0

你需要PIVOT ......這裏http://stackoverflow.com/questions/7674786/mysql-pivot-table – Kostis

+0

看看如果是我,我會處理這種事情在應用程序代碼 - 更具可擴展性和靈活性。 – Strawberry

+0

I.e.做一個GROUP BY,用例表達式來做條件聚合。 – jarlh

回答

0

試試這個(支點)查詢 -

SELECT 
    bill_no, 
    MAX(IF(alcohol_typ = 's' AND origin = 'f', `2000ml`, NULL)) AS s_f_2000ml, 
    MAX(IF(alcohol_typ = 's' AND origin = 'f', `1000ml`, NULL)) AS s_f_1000ml, 
    MAX(IF(alcohol_typ = 'm' AND origin = 'w', `2000ml`, NULL)) AS m_w_2000ml, 
    MAX(IF(alcohol_typ = 'm' AND origin = 'w', `1000ml`, NULL)) AS m_w_1000ml, 
    bill_date 
FROM permit_bills 
    GROUP BY bill_no, bill_date