相信大家在做使用sql做数据分析的时候,肯定有遇到过这样的情况:需要将某几个字段的column转换到一个字段中,每个column的数据就会呈现在一个字段当中,并进行进一步的查看和分析。
比如说这样的情况:
输入: Products table: +------------+--------+--------+--------+ | product_id | store1 | store2 | store3 | +------------+--------+--------+--------+ | 0 | 95 | 100 | 105 | | 1 | 70 | null | 80 | +------------+--------+--------+--------+ 输出: +------------+--------+-------+ | product_id | store | price | +------------+--------+-------+ | 0 | store1 | 95 | | 0 | store2 | 100 | | 0 | store3 | 105 | | 1 | store1 | 70 | | 1 | store3 | 80 | +------------+--------+-------+
以上这种情况就是将字段转换为数据,合并各个字段中的数据来查看总体的数据情况。
那么做到这样的方法在Mysql中常见的作法就是使用union
,是的,就是使用将两张及以上数据表合并在一起的union
函数,这样做的想法就是将每个字段及其数据和其他的字段选出,看作一张表,通过多次对原数据的select,就可以将原始数据进行列转行的操作。
附上代码:
select product_id,'store1' as store ,store1 as price from Products
where store1 is not null
union all
select product_id,'store2' as store ,store2 from Products
where store2 is not null
union all
select product_id,'store3' as store ,store3 from Products
where store3 is not null
order by store
还有一种使用union的情形,分类讨论
比如在我们要对某一字段进行分组,而在表中没有现成的类别时,这个时候直接使用其他的方法来将不同类别呈现在同一列中就显得比较麻烦,使用union
就可以快速的解决这样的问题
输入:
Accounts 表:
+------------+--------+
| account_id | income |
+------------+--------+
| 3 | 108939 |
| 2 | 12747 |
| 8 | 87709 |
| 6 | 91796 |
+------------+--------+
输出:
+----------------+----------------+
| category | accounts_count |
+----------------+----------------+
| Low Salary | 1 |
| Average Salary | 0 |
| High Salary | 3 |
+----------------+----------------+
同样地,附上代码:
select 'Low Salary' as category,
sum(income <20000) as accounts_count
from Accounts
union
select 'Average Salary' as category,
sum(income <=50000 and income >=20000) as accounts_count
from Accounts
union
select 'High Salary' as category,
sum(income >50000) as accounts_count
from Accounts