数据库行转列、列转行、去重问题

本文介绍了SQL中的两种数据转换方法:列转行和行转列,并提供了实际示例。列转行通过DECODE函数实现,将特定列的值按行展示;行转列则使用UNION ALL进行多条SQL查询组合。此外,还讲解了如何在多列中去重,特别是针对只有一列存在重复时的处理方法,利用COUNT(DISTINCT)函数配合GROUP BY达到去重目的。
摘要由CSDN通过智能技术生成

1、列转行

select year,
– 当 a.month 的值 为 1 时 取值 a.index 否则 为 0 并取别名 为 index*

max(DECODE(a.month,'1',a.index,'0')) as index1,
max(DECODE(a.month,'2',a.index,'0')) as index2,
max(DECODE(a.month,'3',a.index,'0')) as index3,
max(DECODE(a.month,'4',a.index,'0')) as index4 
from test_2020_11_12 a group by year

原先结果:
year month index
2021 3 t1
2021 3 t1
2021 2 t1
2021 2 t1
2021 1 t1
2021 1 t1
2021 4 t1
2021 4 t1

转换以后的结果:
Year index1 index2 index3 index4
2021 t1 t2 t3 t4
2021 t1 t2 t3 t4

2、行转列

    select  year, '1' as month,index1 as index    from col_to_row
union ALL 
select  year, '2' as month, index1 as index    from col_to_row
union ALL 
select    year,  '3' as month,  index1 as index   from col_to_row
UNION ALL 
select  year,  '4' as month, index1 as index   from col_to_row

原先结果:
Year index1 index2 index3 index4
2021 t1 t2 t3 t4
2021 t1 t2 t3 t4

转换之后结果:
year month index
2021 3 t1
2021 3 t1
2021 2 t1
2021 2 t1
2021 1 t1
2021 1 t1
2021 4 t1
2021 4 t1

3、去重问题

针对多列中 只有一列时重复的
参考的文档 :

https://blog.csdn.net/djun100/article/details/84473838?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.pc_relevant_is_cache&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.pc_relevant_is_cache

SQL :select *, count(distinct name) from table group by name
具体的例子:

select *,count(DISTINCT  sex) from   demo2  a
JOIN  demo1  b
ON a.id=b.id
where ----- 9月1号 到 9月 15 的数据
TO_DATE(CONCAT(SUBSTR(date,1,4),SUBSTR(date,6,2),SUBSTR(date,9,2)),'yyyymmdd') > 
TO_DATE(CONCAT(SUBSTR("2020-09-01",1,4),SUBSTR("2020-09-01",6,2),SUBSTR("2020-09-01",9,2)),'yyyymmdd') 
and 
TO_DATE(CONCAT(SUBSTR(date,1,4),SUBSTR(date,6,2),SUBSTR(date,9,2)),'yyyymmdd') <
TO_DATE(CONCAT(SUBSTR("2020-11-12",1,4),SUBSTR("2020-11-12",6,2),SUBSTR("2020-11-12",9,2)),'yyyymmdd') 
and b.type='学生' and b.name="张三" and a.color='0' GROUP by sex
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值