日期:2014-05-18 浏览次数:20486 次
CREATE TABLE Test ( ID INT IDENTITY , LineID INT , LineName VARCHAR(20) , ClassDate DATETIME , SaleInfo VARCHAR(50) ) go INSERT INTO dbo.Test ( LineID , LineName , ClassDate , SaleInfo ) SELECT 1000 , -- LineID - int '线路1' , -- LineName - varchar(20) '2012-07-09' , -- ClassDate - datetime '45/40/25' -- SaleInfo - varchar(50) UNION ALL SELECT 1000 , -- LineID - int '线路1' , -- LineName - varchar(20) '2012-07-10' , -- ClassDate - datetime '40/40/0' -- SaleInfo - varchar(50) UNION ALL SELECT 1000 , -- LineID - int '线路1' , -- LineName - varchar(20) '2012-07-11' , -- ClassDate - datetime '45/2/0' -- SaleInfo - varchar(50) UNION ALL SELECT 1001 , -- LineID - int '线路2' , -- LineName - varchar(20) '2012-07-09' , -- ClassDate - datetime '50/50/48' -- SaleInfo - varchar(50) UNION ALL SELECT 1001 , -- LineID - int '线路2' , -- LineName - varchar(20) '2012-07-10' , -- ClassDate - datetime '55/30/0' -- SaleInfo - varchar(50) UNION ALL SELECT 1001 , -- LineID - int '线路2' , -- LineName - varchar(20) '2012-07-11' , -- ClassDate - datetime '50/5/0'
---------------------------- -- Author :fredrickhu(小F,向高手学习) -- Date :2012-07-09 11:17:47 -- Version: -- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86) -- Apr 22 2011 11:57:00 -- Copyright (c) Microsoft Corporation -- Enterprise Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64) -- ---------------------------- --> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([ID] int,[LineID] int,[LineName] varchar(5),[ClassDate] datetime,[SaleInfo] varchar(8)) insert [tb] select 1,1000,'线路1','2012-07-09','45/40/25' union all select 2,1000,'线路1','2012-07-10','40/40/0' union all select 3,1000,'线路1','2012-07-11','45/2/0' union all select 4,1001,'线路2','2012-07-09','50/50/48' union all select 5,1001,'线路2','2012-07-10','55/30/0' union all select 6,1001,'线路2','2012-07-11','50/5/0' --------------开始查询-------------------------- declare @sql varchar(8000) set @sql = 'select LineID ,LineName' select @sql = @sql + ' , max(case convert(varchar(10),ClassDate,120) when ''' + convert(varchar(10),ClassDate,120) + ''' then SaleInfo else '''' end) [' + convert(varchar(10),ClassDate,120) + ']' from (select distinct convert(varchar(10),ClassDate,120) as ClassDate from tb) as a set @sql = @sql + ' from tb group by LineID,LineName' exec(@sql) ----------------结果---------------------------- /* LineID LineName 2012-07-09 2012-07-10 2012-07-11 ----------- -------- ---------- ---------- -------