按品牌但不同日期获取总和(销售额)组的语法

Syntax to get sum(sales) group by brand but different date

我的数据是这样的

item        date        country    sales
----------------------------------------
motorola    2015-01-01     US        10
motorola    2015-01-01     UK        20
motorola    2015-01-02     US        40
motorola    2015-01-02     UK        80
motorola    2015-01-03     US       120
motorola    2015-01-03     UK       150
motorola    2015-01-04     US       170
motorola    2015-01-04     US       180

我想获取摩托罗拉从 2015 年 1 月 2 日到 2015 年 1 月 4 日的每日销售增量。

例如

我期待结果元组:

date         dailyDelta
2015-01-02      90
2015-01-03     150
2015-01-04      80

得到这个的语法是什么?我正在使用 SQL Server 2012。

谢谢

我真的没有看到很多解决自连接的方法。这是它的工作原理:

select a.date
  , a.item
  , sum(a.sales) - sum(b.sales) as DailyDelta
from table a
  join table b on a.product = b.product
    and b.date = dateadd(day, -1, a.date)
group by a.date
  , a.item

性能不佳,但可以完成工作。

就是这样,查询逻辑很简单,性能优于内连接:

select date, sum(sales) - coalesce(lag(sum(sales), 1) over (order by date), 0)
from my_sales
group by date
order by date

使用window函数lag。玩一下:http://sqlfiddle.com/#!6/bebab/8 and read about it: https://msdn.microsoft.com/en-us/library/hh231256.aspx

简而言之,lag(sum(sales), 1) over (order by date)表示"get sum(sales) column of previous record of this query, ordered by date",coalesce(XXX, 0)表示"when XXX is null, let's pretend it was a zero"

以下查询基于 MySQL,但您可以调整它以使其适用于 SQL 服务器。希望SQL服务器也能支持

select o.date, t.tsales - sum(sales) delta  from test o, (select date, sum(sales) tsales from test group by date) t
where o.date = t.date -1 group by o.date

对于上述查询,我​​得到了以下结果

"date" "delta" 《2015-01-01》《90后》 "2015-01-02" "150" “2015-01-03”“80”

使用自连接

declare @t table (item varchar(10), [date] date,country  char(2),  sales int)
insert into @t (item, [date],country,  sales) values
('motorola','2015-01-01','US',10),
('motorola','2015-01-01','UK',20),
('motorola','2015-01-02','US',40),
('motorola','2015-01-02','UK',80),
('motorola','2015-01-03','US',120),
('motorola','2015-01-03','UK',150),
('motorola','2015-01-04','US',170),
('motorola','2015-01-04','US',180)
;with a as (select row_number() over (order by [date]) r,[date],sum(sales) n from @t group by [date]) 

select a.[date],a.n-isnull(a1.n,0) dailyDelta from a  join a a1 on a.r =a1.r+1

试试这个..

SELECT 日期,

  ( sum(sales) - LAG(sum(sales),1,0) over (order by sales) ) as dailyDelta

从Table

按日期分组

按日期排序;