[英]Selecting rows as columns in MYSQL
你好,我想弄清楚如何做到這一點,我有一個 mysql 表
| ID | ACC_ID | line_id | code |
| 1 | 1 | 5960 | DCA |
| 2 | 1 | 5960 | AAA |
| 3 | 1 | 5960 | DDD |
| 4 | 1 | 5960 | DER |
| 5 | 1 | 5054 | DCB |
| 6 | 1 | 5054 | AAC |
| 7 | 1 | 5011 | DDE |
| 8 | 1 | 5012 | DEQ |
等數據庫下降了大約 10000 行
我想做一個 mysql select 語句來執行此操作
| ACC_ID | line_id | code | code | code | code |
| 1 | 5960 | DCA | AAA | DDD | DER |
| 1 | 5054 | DCB | DER | | |
| 1 | 5011 | DDE | | | |
| 1 | 5012 | DEQ | | | |
每個 line_id 最多可以有十個代碼
現在我的問題是可以使用 select 語句進行上面的查詢。
謝謝大家的幫助
這是一個PIVOT
但 MySQL 沒有PIVOT
函數,但您可以使用聚合函數和CASE
語句復制它。 MySQL 也沒有按組分配行號的最簡單方法,但以下是如何使用 SQL 實現此目的的示例。 由於您說每個line_id
最多可以有 10 個代碼, line_id
我硬編碼了一個可能的解決方案。:
select acc_id,
line_id,
max(case when group_row_number = 1 then code end) Code1,
max(case when group_row_number = 2 then code end) Code2,
max(case when group_row_number = 3 then code end) Code3,
max(case when group_row_number = 4 then code end) Code4,
max(case when group_row_number = 5 then code end) Code5,
max(case when group_row_number = 6 then code end) Code6,
max(case when group_row_number = 7 then code end) Code7,
max(case when group_row_number = 8 then code end) Code8,
max(case when group_row_number = 9 then code end) Code9,
max(case when group_row_number = 10 then code end) Code10
from
(
select ACC_ID,
line_id,
code,
@num := if(@ACC_ID = `ACC_ID` AND @line_id = `line_id`, @num + 1, 1) as group_row_number,
@ACC_ID := `ACC_ID` as dummy,
@line_id := `line_id` as linedummy
from yourtable
) src
group by acc_id, line_id
order by line_id desc
結果:
| ACC_ID | LINE_ID | CODE1 | CODE2 | CODE3 | CODE4 | CODE5 | CODE6 | CODE7 | CODE8 | CODE9 | CODE10 |
-------------------------------------------------------------------------------------------------------------
| 1 | 5960 | DCA | AAA | DDD | DER | (null) | (null) | (null) | (null) | (null) | (null) |
| 1 | 5054 | DCB | AAC | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 1 | 5012 | DEQ | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 1 | 5011 | DDE | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.