天天看點

mysql 行轉列示例

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函數