2016-06-24 21 views
3

我有一個表的命令是看起來像:SQL和數據

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 

我知道這是錯的,但是這是在我腦海中的邏輯。

你可以給我一些想法如何做到這一點?

+1

請提供測試數據以及 – TheGameiswar

回答

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 
+0

作品!太好了!謝謝 –

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