sql 语句实现
数据库table:
id time count
1 8:00-9:00 60
2 9:00-10:00 80
3 10:00-11:00 40
1 9:00-10:00 69
1 。
。
。
我想sql语句查出来后是这种效果:
id 8:00-9:00 9:00-10:00 10:00-11:00 。。。。。
1 60 69
[解决办法]
就是行转列,很多例子,等楼下代码详解。
[解决办法]
if object_id('[TB]') is not null drop table [TB]gocreate table [TB] (id int,time nvarchar(22),count int)insert into [TB]select 1,'8:00-9:00',60 union allselect 2,'9:00-10:00',80 union allselect 3,'10:00-11:00',40 union allselect 1,'9:00-10:00',69select * from [TB]select ID,MAX(case when time ='8:00-9:00' then [COUNT] else 0 end ) as '8:00-9:00',MAX(case when time ='9:00-10:00' then [COUNT] else 0 end ) as '9:00-10:00',MAX(case when time ='10:00-11:00' then [COUNT] else 0 end ) as '10:00-11:00'from TBgroup by id/*ID 8:00-9:00 9:00-10:00 10:00-11:00----------- ----------- ----------- -----------1 60 69 02 0 80 03 0 0 40(3 行受影响)
[解决办法]
IF OBJECT_ID('tab') IS NOT NULL DROP TABLE tabCREATE TABLE TAB(id INT,[TIME] VARCHAR(20),[COUNT] INT)INSERT INTO tabSELECT 1, '8:00-9:00', 60 UNION ALLSELECT 2, '9:00-10:00', 80 UNION ALLSELECT 3, '10:00-11:00', 40 UNION ALLSELECT 1, '9:00-10:00' ,69DECLARE @timeProperty VARCHAR(max)declare @sql varchar(max)SET @timeProperty=''SELECT @timeProperty=@timeProperty+','+'['+[time]+']' FROM tab GROUP BY [time]SET @timeProperty=STUFF(@timeProperty,1,1,'')set @sql='SELECT * FROM tab PIVOT ( SUM([COUNT]) FOR [time] IN ('+@timeProperty+') ) AS p'EXEC (@sql)/*id 10:00-11:00 8:00-9:00 9:00-10:00----------- ----------- ----------- -----------1 NULL 60 692 NULL NULL 803 40 NULL NULL*/
[解决办法]