替代文字http://agricam.net/test.gif
我需要在市场营销人数改变之后在SQL中动态添加一行,其中标题为"Marketer Total",只应添加"Total"列.例如,在Marketer 22行的最后一行之后,应该有"Marketer Total",然后在Total列下面应该是1804.同样应该在Marketer 500的最后一行之后发生.
请参见http://agricam.net/test.gif上的图片
当前查询:
从SomeTable中选择Marketer,SubMarketer,Grade,Total,Convert(varchar,Date,101)[Date],其中Date> ='2/25/2009'和Date <'2/26/2009'和Marketer in('22' ,'500')分组由SubMarketer,Grade,Marketer,Date,总订单由Marketer提供
谢谢.
请参阅 使用ROLLUP在SQL中聚合数据
执行:
DECLARE @SOMETABLE TABLE (SUBMARKETER INT, GRADE CHAR, MARKETER INT, DATE DATETIME, TOTAL INT) INSERT INTO @SOMETABLE SELECT 1415, 'A', 22, '02/25/2009', 26 UNION SELECT 1415, 'B', 22, '02/25/2009', 93 UNION SELECT 1415, 'C', 22, '02/25/2009', 1175 UNION SELECT 1415, 'D', 22, '02/25/2009', 510 UNION SELECT 1169, 'B', 500, '02/25/2009', 1 UNION SELECT 1169, 'C', 500, '02/25/2009', 3 UNION SELECT 1393, 'C', 500, '02/25/2009', 2 UNION SELECT 2, 'B', 500, '02/25/2009', 5 UNION SELECT 2, 'C', 500, '02/25/2009', 111 UNION SELECT 2, 'D', 500, '02/25/2009', 18 SELECT CASE WHEN SUBMARKETER IS NULL THEN 'Marketer Total' ELSE CONVERT(VARCHAR, MARKETER) END MARKETER, SUBMARKETER, GRADE, TOTAL, DATE FROM ( SELECT MARKETER, SUBMARKETER, GRADE, SUM(TOTAL) AS TOTAL, CONVERT(VARCHAR,DATE,101)[DATE] FROM @SOMETABLE WHERE DATE >= '2/25/2009' AND DATE < '2/26/2009' AND MARKETER IN ('22','500') GROUP BY MARKETER, SUBMARKETER, GRADE, DATE WITH ROLLUP )M WHERE M.MARKETER IS NOT NULL AND NOT (SUBMARKETER IS NOT NULL AND DATE IS NULL)
注意:如果MARKETER,SUBMARKETER和DATE列不为NULL,这将正常工作.如果表中的theese字段将有NULL值,那么过滤掉无用的分组将成为一个问题.