SQL汇总数据在一列中的两个日期之间

时间:2016-06-24 07:57:40

标签: sql sql-server date sum

我的订单表格如下:

T1

+-----------+---------+------------+
| client ID | order q | order date |
+-----------+---------+------------+
|     01    |  100    | 01-02-2016 |
|     01    |  350    | 03-05-2016 |
+-----------+---------+------------+

我有第二张销售表:

T2

+-----------+-------+------------+
| client ID | sales | sales date |
+-----------+-------+------------+
|   01      | 50    | 03-02-2016 |
|   01      | 50    | 10-02-2016 |
|   01      | 300   | 04-05-2016 |
|   01      | 50    | 15-05-201  |
+-----------+-------+------------+  

目标是使销售额SUM超过第一个订单日期而不是第二个订单日期:

结果

+-----------+---------+-------+
| cliend ID | order q | sales |
+-----------+---------+-------+
|  01       | 100     | 100   |
|  01       | 350     | 350   |
+-----------+---------+-------+

首先想法是将订单日期评为

DENSE_RANK() OVER(PARTITION BY [client ID] ORDER BY [order date] ASC) AS R

然后做这样的事情:

select
    client ID,
    order q,
    sum (sales) as sales
from 
    t2  
left outer join
    t2.client ID = t1.client ID
where 
    [sales date] >= [order date] 
    and [sales date] <= [order date] in (select [order date] 
                                         from t2 
                                         where (R < (R+1)))
group by 
    client ID, order q

我知道这是错的,但这是我头脑中的逻辑。

你能告诉我一些如何做到这一点的想法吗?

2 个答案:

答案 0 :(得分:1)

看起来是日期之间的总和。我假设包括当前订单日期,不包括下一个订单日期。

select t.clientID, fromdate, sum(sales) 
from (
    select clientID,orderq
        , fromdate = orderdate
        , todate = dateadd(dd, -1, lead(orderdate,1,cast('2100-01-01' as date)) over(partition by clientID order by orderdate))
    from(
            values
            (01,100,cast('2016-02-01' as date)),
            (01,350,cast('2016-05-03' as date))
        ) orders(clientID,orderq,orderdate)
    ) t
join( 
        values  
        (01,50  ,cast('2016-02-03' as date)),
        (01,50  ,cast('2016-02-10' as date)),
        (01,300 ,cast('2016-05-04' as date)),
        (01,50  ,cast('2016-05-15' as date))
    ) sales(clientID, sales,salesdate)
    on sales.salesdate between fromdate and todate
group by t.clientID, fromdate   

答案 1 :(得分:0)

试试这个:

;WITH CTE AS (
  SELECT [client ID], [order q], [order date],         
         COALESCE(LEAD([order date]) OVER (PARTITION BY [client ID] 
                                          ORDER BY [order date]),
                '2100-01-01') AS Next_Date
  FROM t1
)
SELECT t1.[client ID], t1.[order q], t2.sales
FROM CTE AS t1
CROSS APPLY (
   SELECT [client ID], SUM(sales) AS  sales
   FROM t2
   WHERE [sales date] > t1.[order date] AND [sales date] < t1.Next_Date
   GROUP BY [client ID]) AS t2

Demo here