当前位置:  开发笔记 > 编程语言 > 正文

Sql分组

如何解决《Sql分组》经验,为你挑选了1个好方法。

替代文字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提供

谢谢.



1> Maksym Gonta..:

请参阅 使用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值,那么过滤掉无用的分组将成为一个问题.

推荐阅读
依然-狠幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有