mysql括號裡的行轉豎直 mysql 行轉列示例

2021-10-19 21:29:25 字數 1930 閱讀 4948

1.原始sql:

mysql> select (select t.name from dimension t where t.id=rule_dimension.dimension_id) as name,getdimensionvalue(rule_id,dimension_id,2) as 'vts'

from rule_dimension where rule_id=1 and status=0;

| name | vts |

| 地域 | 北京,上海 |

| 時段 | 4點 |

| 頻道 | 科技 |

最終想得到的資料格式:地域:(北京,上海) and 時段:(4點) and 頻道:(科技)

即:把多行資料顯示到一行——行轉列。這裡主要用到了group_concat函式

2.把兩列資料合併成一列顯示:

select concat_ws(':',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getdimensionvalue(rule_id,dimension_id,2)) as ct

from rule_dimension where rule_id=1 and status=0;

| ct             |

| 地域:北京,上海 |

| 時段:4點       |

| 頻道:科技      |

3 rows in set

這裡主要用到了concat_ws函式,把多列資料合併成一列;

3.把多行轉換成一行顯示(行轉列)

select group_concat(concat_ws(':',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getdimensionvalue(rule_id,dimension_id,2)) separator ' and ') as ct

from rule_dimension where rule_id=1 and status=0;

| ct                                    |

| 地域:北京,上海 and 時段:4點 and 頻道:科技 |

1 row in set這裡主要用到了group_concat函式,可以使用separator指定連線符號;

4.修正結果

select group_concat(concat_ws(':(',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getdimensionvalue(rule_id,dimension_id,2)) separator ') and ') as ct

from rule_dimension where rule_id=1 and status=0;

| ct |

| 地域:(北京,上海) and 時段:(4點) and 頻道:(科技 |

1 row in set這裡主要還是用到了concat_ws函式,把括號加上了

5.補充最後乙個括號:

select concat(group_concat(concat_ws(':(',(select t.name from dimension t where t.id=rule_dimension.dimension_id) ,getdimensionvalue(rule_id,dimension_id,2)) separator ') and '),')') as ct

from rule_dimension where rule_id=1 and status=0;

| ct |

| 地域:(北京,上海) and 時段:(4點) and 頻道:(科技) |

1 row in set 這裡還是用到了concat函式

mysql 動態行轉列 MySQL行轉列

比如乙個單子,多個收據單用逗號隔開,怎麼把這乙個單子所有收據單獨展示出來,行轉成列呢?方法一 這裡需要用到迴圈,首先建立乙個1 10的序列 select rownum rownum 1 as seq from select rownum 0 r,bills limit 0,10 其次依次運用 sub...

mysql行轉列 subs mysql 行轉列

存在表score,記錄學生的考試成績,如下圖所示 現要求以 學生姓名,語文,數學,英語 這種格式顯示學生成績,如下圖所示 具體步驟如下 1 首先,使用case when函式輸出單個課程的成績 case when course 語文 then score end as 語文 case when cou...

mysql行轉列怎麼用 mysql錶行轉列的用法

現在有一張score表,儲存學生每門課的成績,結構資料如下 idnamesubjectscore 1張三 語文90 2張三 數學88 3張三 外語75 4李四 語文99 5李四 數學70 6李四 外語95 7李五 語文88 8李五 數學85 9李五 外語90 現在要求列出每個學生所有課程的成績.這就...