select Name, 
max(日期),
sum(销售量),
sum(select 销售量 from table B where A.name = B.name and datediff(month,B.日期,0) = datediff(month,A.日期,0) - 1 ) as 上月同期
sum(销售量) - sum(select 销售量 from table B where A.name = B.name and datediff(month,B.日期,0) = datediff(month,A.日期,0) - 1 ) as 增减,
sum(select 销售量 from table B where A.name = B.name and datediff(month,B.日期,0) = datediff(month,A.日期,0) - 12 ) as 上年同期
sum(销售量) - sum(select 销售量 from table B where A.name = B.name and datediff(month,B.日期,0) = datediff(month,A.日期,0) - 12 ) as 增减,
from table A
group by Name, Datediff(month,日期,0)
//未测试。

解决方案 »

  1.   

    头有点大……
    table B 是什么意思?我的表中已经包括了本月、上月、上年的数据,那么
    WHERE A.NAME = B.NAME 显然不成立。
    原本打算用2个DBGrid的,就是两个数据集,但考虑到增减分析及打印的问题
    没用。
      

  2.   

    table  B  是用B作为table的别名。成立的,这只是一个子查询而已。
      

  3.   

    select Name,
    max(日期),
    sum(销售量),
    sum(select 销售量 from table B where A.name = B.name and datediff(month,B.日期,0) = datediff(month,A.日期,0) - 1 ) as 上月同期
    from table A
    group by Name, Datediff(month,A.日期,0)在SQL SERVER下应该是没有问题的。
      

  4.   

    SORRY, 我在试 SUM(SELECT 字段1 FROM TABLE1) 好像就不行,然后试 SELECT SUM(字段1) FROM TABLE1 可以是可以,但GROUP BY 出来就是一个值了。可怜
      

  5.   

    显示的字段1 应是int型
      

  6.   

    是INT型,要不我SUM什么,我是在查询分析器中做的。
      

  7.   

    SELECT SUM(字段1) FROM TABLE1 
    where ...有没有加?