MySQL 行变列 查询

SQL语言的CASE语句备忘
 
概述:
SQL语句中的CASE语句与高级语言中的switch语句,是标准SQL的语法,适用与一个条件判断有多种值的情况下分别执行不同的操作。灵活应用CASE语句可以使SQL语句变得简洁易读,下面在DB2环境下通过一个简单的查询来展示SQL CASE语句的强大功能。

 

表:T_ActivityConsume

 

award consumeTime partnerID markValue
1 2009-01-05 13:14:43 11 100
1 2009-01-05 13:14:43 11 100
3 2009-01-05 13:14:43 11 100
1 2009-01-06 13:14:43 11 100
1 2009-01-06 13:14:43 11 100
2 2009-01-17 13:14:43 11 100
2 2009-01-17 13:14:43 11 100
2 2009-01-17 13:14:43 11 100
1 2009-01-17 13:14:43 11 100

 

 


      select award ,

          COUNT(CASE when DATE(consumeTime)='2009-01-05' then award end) as '1月5日',

          count(CASE when DATE(consumeTime)='2009-01-06' then award end) as '1月6日',
          count(CASE when DATE(consumeTime)='2009-01-07' then award end) as '1月7日'
      from T_ActivityConsume where partnerID='11' group by award

 

 

执行后:

award partnerID 1月5日 1月6日 1月7日
1 11 2 2 1
2 11 0 0 3
3 11 1 0 0
4 11 0 0 0
5 11 0 0 0

 

 

case和swith类似。

你可能感兴趣的:(sql,mysql,db2)