日期:2014-05-18 浏览次数:20636 次
if object_id('中间表') is not null exec('drop table 中间表') EXEC(@sql+',[合计]=SUM(数量) INTO [中间表] FROM (SELECT 工厂名称,产品号,数量,日期=CONVERT(CHAR(10),日期,120) FROM T) A GROUP BY 日期 WITH ROLLUP ')
------解决方案--------------------
--应该可以的啊,只不过不能使用临时表 CREATE TABLE T ( 工厂名称 VARCHAR(20), 产品号 VARCHAR(20), 数量 INT, 日期 DATETIME ) INSERT INTO T SELECT 'a','6800',51,'2007-5-14' UNION ALL SELECT 'b','6800',52,'2007-5-14' UNION ALL SELECT 'a','1920',53,'2007-5-14' UNION ALL SELECT 'a','6800',54,'2007-5-15' UNION ALL SELECT 'a','1920',54,'2007-5-15' UNION ALL SELECT 'b','6800',54,'2007-5-15' GO select * from T DECLARE @sql VARCHAR(8000) SET @sql='SELECT 日期=CASE WHEN GROUPING(日期)=1 THEN ''合计'' ELSE 日期 END' SELECT @sql=@sql+',['+产品号+'-'+工厂名称+']=ISNULL(SUM(CASE WHEN 工厂名称 ='''+工厂名称+''' AND 产品号='''+产品号+'''THEN 数量 END),0)' FROM (SELECT 产品号 FROM T GROUP BY 产品号)A,(SELECT 工厂名称 FROM T GROUP BY 工厂名称)B ORDER BY 产品号 DESC,工厂名称 EXEC(@sql+',[合计]=SUM(数量) INTO T1 FROM (SELECT 工厂名称,产品号,数量,日期=CONVERT(CHAR(10),日期,120) FROM T)A GROUP BY 日期 WITH ROLLUP') SELECT * FROM T1 DROP TABLE T1 DROP TABLE T CREATE TABLE T ( 工厂名称 VARCHAR(20), 产品号 VARCHAR(20), 数量 INT, 日期 DATETIME ) INSERT INTO T SELECT 'a','6800',51,'2007-5-14' UNION ALL SELECT 'b','6800',52,'2007-5-14' UNION ALL SELECT 'a','1920',53,'2007-5-14' UNION ALL SELECT 'a','6800',54,'2007-5-15' UNION ALL SELECT 'a','1920',54,'2007-5-15' UNION ALL SELECT 'b','6800',54,'2007-5-15' GO select * from T DECLARE @sql VARCHAR(8000) SET @sql='SELECT 日期=CASE WHEN GROUPING(日期)=1 THEN ''合计'' ELSE 日期 END' SELECT @sql=@sql+',['+产品号+'-'+工厂名称+']=ISNULL(SUM(CASE WHEN 工厂名称 ='''+工厂名称+''' AND 产品号='''+产品号+'''THEN 数量 END),0)' FROM (SELECT 产品号 FROM T GROUP BY 产品号)A,(SELECT 工厂名称 FROM T GROUP BY 工厂名称)B ORDER BY 产品号 DESC,工厂名称 EXEC(@sql+',[合计]=SUM(数量) INTO T1 FROM (SELECT 工厂名称,产品号,数量,日期=CONVERT(CHAR(10),日期,120) FROM T)A GROUP BY 日期 WITH ROLLUP') SELECT * FROM T1 DROP TABLE T1 DROP TABLE T