1. case when条件筛选,实现行转列

学生的成绩表(表名score,列名:学号,课程号,成绩)
sql实现行转列为下面的表结构
image.png

答案:
image.png

2.case when条件筛选,统计某个分类的个数

计算好评率
image.png

  1. select count(1) '总评价数',
  2. sum(case when sat_name='好评' then 1 else 0 end) '好评数',
  3. sum(case when sat_name='好评' then 1 else 0 end)/count(1) as '好评率'
  4. from reddk_userjudge a
  5. join reddk_goodsinfo b
  6. on a.goods_id=b.goods.id
  7. where a.user_name='小张'
  8. and sub_time between '2019-01-01' and '2019-03-31'
  9. and b.goods_name = '母婴'
  10. and b.brand_name = 'DW'

3. 用户已购买/购买未收藏/收藏未购买/收藏且购买

image.png

  1. select a.user_id,
  2. a.item_id,
  3. 1 as '已购买',
  4. (case when fav_time is null then 1 else 0 end)as '购买未收藏',
  5. 0 as '收藏未购买',
  6. (case when fav_time is not null then 1 else 0 end)as '收藏且购买'
  7. from redbk_orders a
  8. left join redbk_favorites b
  9. on a.user_id=b.user_id and a.itme_id=b.item.id
  10. union
  11. select b.user_id,
  12. b.item_id,
  13. (case when par_time is not null then 1 else 0 end) as '已购买',
  14. 0 as '购买未收藏',
  15. (case when par_time is null then 1 else 0 end) as '收藏未购买',
  16. (case when par_time is not null then 1 else 0 end)as '收藏且购买'
  17. from redbk_orders a
  18. right join redbk_favorites b
  19. on a.user_id=b.user_id and a.itme_id=b.item.id

4.

image.png

  1. 1.
  2. select sum(case when '单量'<=5 then 1 else 0 end) as '0-5',
  3. sum(case when '单量' between 6 and 10 then 1 else 0 end) as '6-10',
  4. sum(case when '单量' between 11 and 20 then 1 else 0 end) as '11-20',
  5. sum(case when '单量' >=20 then 1 else 0 end) as '20以上'
  6. from (
  7. select count(distinct order_id) as '单量'
  8. from table
  9. where year(t_date)=2020 and month(t_date)=5
  10. group by user_id
  11. ) as t
  12. 2.输出对应的表格
  13. create table t1 as
  14. select count(distinct order_id) as '订单数'
  15. from table
  16. where year(t_date)=2020 and month(t_date)=5
  17. group by user_id;
  18. select '0-5' as '单量', sum(case when '订单数'<=5 then 1 else 0 end) as '客户数' from t1
  19. union
  20. select '6-10' as '单量', sum(case when '订单数' between 6 and 10 then 1 else 0 end) as '客户数' from t1
  21. union
  22. select '11-20' as '单量', sum(case when '订单数' between 11 and 20 then 1 else 0 end) as '客户数' from t1
  23. union
  24. select '20 以上' as '单量', sum(case when '订单数' >=20 then 1 else 0 end) as '客户数' from t1