日期:2014-05-18  浏览次数:20749 次

感觉有点难度的SQL语句
OrderID StyleID SizeName StyleColor StyleBrand StyleListQty 
----------- ------- -------------------- ------------------------------ -------------------- ------------ 
16 2 1 Black 300
16 2 3 Black 300
16 2 5 Black 200
16 2 7 Black 800
16 2 9 Black 200
16 2 11 Black 200

(所影响的行数为 6 行)


有如上数据纪录,有没有什么语句可以实现如下结果?

OrderID StyleID 1 3 5 7 9 11 StyleColor StyleBrand  
----------- ------- --- --- --- --- --- --- -------------------- ------------ 
16 2 300 300 200 800 200 200 Black  

谢谢帮忙!

------解决方案--------------------
练个手!:)

CREATE TABLE T

OrderID INT,
StyleID INT,
SizeName VARCHAR(20),
StyleColor VARCHAR(20),
StyleBrand VARCHAR(20),
StyleListQty INT
)

INSERT INTO T
SELECT 16,2,1,'Black',NULL, 300 UNION ALL
SELECT 16,2,3,'Black',NULL, 300 UNION ALL
SELECT 16,2,5,'Black',NULL, 200 UNION ALL
SELECT 16,2,7,'Black',NULL, 800 UNION ALL
SELECT 16,2,9,'Black',NULL, 200 UNION ALL
SELECT 16,2,11,'Black',NULL, 200

 DECLARE @sql VARCHAR(8000)
SELECT @sql = 'SELECT OrderID, StyleID'
SELECT @sql = @sql + ',['+SizeName+'] = SUM(CASE WHEN SizeName = '''+SizeName+''' THEN StyleListQty END)'
FROM T GROUP BY SizeName
EXEC( @sql + ',StyleColor,StyleBrand FROM T GROUP BY OrderID,StyleID,StyleColor,StyleBrand ORDER BY OrderID,StyleID' )

DROP TABLE T
------解决方案--------------------
SQL code

create table tb (OrderID int,StyleID int,SizeName int,StyleColor varchar(20),StyleBrand varchar(50),StyleListQty int)
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty) select 16 , 2 ,1,'Black',300 
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty)  select 16,2   ,    3   ,                 'Black'         ,                                      300 
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty)  select 16 ,         2   ,    5      ,              'Black' ,                                              200 
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty)  select 16 ,         2   ,    7      ,              'Black'   ,                                            800 
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty)  select 16  ,        2   ,    9     ,               'Black'   ,                                            200 
insert into tb(OrderID,styleid,sizename,stylecolor,stylelistqty)  select 16   ,       2   ,   11     ,              'Black'    ,                                           200 

declare @sql varchar(1000)
set @sql='select orderid,styleid'
select @sql=@sql+',['+cast(SizeName as varchar)+']=max(case SizeName when '''+cast(SizeName as varchar)+''' then StyleListQty else 0 end)' from tb 
set @sql=@sql+',stylecolor,stylebrand from tb group by orderid,styleid,stylecolor,stylebrand'
exec(@sql)