【100分】一路SQL面试题,大神求解惑
【100分】一道SQL面试题,大神求解惑!
如表结构
年 月 销售量(万)
2001 1 10
2001 2 11
2001 3 15
2001 4 13
2002 1 15
2002 2 14
2002 3 16
2002 4 17
请问如何查出如下结果:
年 一月 二月 三月 四月
2001 10 11 15 13
2002 15 14 16 17
求大神解惑啊!!!!
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
这种问题坛子里太多了,楼主花点时间看精华帖子,对你一定有用
如表结构
年 月 销售量(万)
2001 1 10
2001 2 11
2001 3 15
2001 4 13
2002 1 15
2002 2 14
2002 3 16
2002 4 17
请问如何查出如下结果:
年 一月 二月 三月 四月
2001 10 11 15 13
2002 15 14 16 17
求大神解惑啊!!!!
------解决方案--------------------
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-16 15:46:53
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([年] int,[月] int,[销售量(万)] int)
insert [huang]
select 2001,1,10 union all
select 2001,2,11 union all
select 2001,3,15 union all
select 2001,4,13 union all
select 2002,1,15 union all
select 2002,2,14 union all
select 2002,3,16 union all
select 2002,4,17
--------------开始查询--------------------------
select 年,SUM(CASE WHEN 月=1 then [销售量(万)] ELSE 0 END )'一月'
,SUM(CASE WHEN 月=2 then [销售量(万)] ELSE 0 END) '二月',
SUM(CASE WHEN 月=3 then [销售量(万)] ELSE 0 END )'三月',
SUM(CASE WHEN 月=4 then [销售量(万)] ELSE 0 END )'四月'
from [huang]
GROUP BY 年
----------------结果----------------------------
/*
年 一月 二月 三月 四月
----------- ----------- ----------- ----------- -----------
2001 10 11 15 13
2002 15 14 16 17
*/
------解决方案--------------------
select
年,
max(case when 月=1 then 销售量 else 0 end) as 一月,
max(case when 月=2 then 销售量 else 0 end) as 二月,
...
from
tb
group by
年
------解决方案--------------------
这种问题坛子里太多了,楼主花点时间看精华帖子,对你一定有用