SQL SUM由多行上的某些值组成

时间:2015-12-30 09:02:53

标签: sql-server group-by sum

我对SQL有疑问。我有以下表格:

     d        x      y          p
 2002-09-05  8.0     8       100.00
 2002-09-06  4.0     24      16.66
 2002-09-09  4.0     8       50.00
 2002-09-10  4.0     8       50.00
 2002-09-11  8.0     8       100.00
 2002-09-12  8.0     8       100.00

如果x相同且y为一个,我想总结pd。下表是我希望看到的结果。

      d1        d2        x      y      p
 2002-09-05 2002-09-05   8.0     8    100.00
 2002-09-06 2002-09-06   4.0     24   16.66
 2002-09-09 2002-09-10   8.0     16   50.00
 2002-09-11 2002-09-12   16.0    16   100.00

到目前为止我做了什么: 我这样做了:

CTE AS 
(SELECT DATEADD(d, - ROW_NUMBER() OVER (PARTITION BY percentage ORDER BY d), d) AS group
, * FROM table)

然后选择了这个。但这不起作用。

SELECT MIN(d) d
,      MAX(d) d1
,      SUM(x) as x
,      SUM(y) as y
,      MAX(p) as p 
FROM   CTE 
GROUP BY group

示例数据:

CREATE TABLE #temp(d date, x decimal(18,9), y decimal(18,9), p decimal(18,9))

insert into #temp values
({d '2002-09-05'}, 8, 8, 100),
({d '2002-09-06'}, 4, 24, 16.66),
({d '2002-09-09'}, 4, 8, 50),
({d '2002-09-10'}, 4, 8, 50),
({d '2002-09-11'}, 8, 8, 100),
({d '2002-09-12'}, 8, 8, 100)

2 个答案:

答案 0 :(得分:0)

我已经使用游标编写了这个脚本,因为你必须根据输出表评估每一行

试试这个:

CREATE TABLE #app (d date, x decimal(18,9), y decimal(18,9), p decimal(18,9))

insert into #app values
({d '2002-09-05'}, 8, 8, 100),
({d '2002-09-06'}, 4, 24, 16.66),
({d '2002-09-09'}, 4, 8, 50),
({d '2002-09-10'}, 4, 8, 50),
({d '2002-09-11'}, 8, 8, 100),
({d '2002-09-12'}, 8, 8, 100)

create table #out (d1 date, d2 date, x decimal(18,9), y decimal(18,9), p decimal(18,9))

declare @d date
declare @x decimal(18,9)
declare @y decimal(18,9)
declare @p decimal(18,9)

declare #crs insensitive cursor for
select d, x, y, p
from #app
order by d, p
for read only
open #crs
fetch next from #crs into @d, @x, @y, @p
while @@fetch_status = 0
begin
    if (select COUNT(*) from #out where p = @p) = 0
    begin
        insert into #out values (@d, @d, @x, @y, @p)
    end
    else 
    begin
        if (select COUNT(*) from #out where (d1 = @d or d2 = @d) and p = @p) > 0
        begin
            update #out set x = x + @x, y = y + @y where (d1 = @d or d2 = @d) and p = @p
        end
        else if (select COUNT(*) from #out where d2 = dateadd(day, -1, @d) and p = @p) > 0
        begin
            update #out set x = x + @x, y = y + @y, d2 = @d where d2 = dateadd(day, -1, @d) and p = @p
        end
        else 
        begin
            insert into #out values (@d, @d, @x, @y, @p)
        end
    end
    fetch next from #crs into @d, @x, @y, @p
end
close #crs
deallocate #crs

select * from #out order by d1

答案 1 :(得分:0)

此解决方案不使用while循环,可能更符合您的需求

SELECT MIN(d) AS d1, MAX(d) AS d2, SUM(x) AS x, SUM(y) AS y, p 
FROM (
    SELECT d,x,y,p,
       DATEADD(dd, - row_number() OVER (PARTITION BY p ORDER BY d), d) AS val
    FROM CTE
)t  
GROUP BY val, p
ORDER BY d1