如何在两个交易日期之间填充数量

时间:2017-06-19 17:33:51

标签: sql-server

我有一张表,其中包含日期,产品,数量(购买是积极的,销售是负数)和价格,如下所示 Date Prod_Name Qty Price 1/3/2017 ProductA 8 150 1/9/2017 ProductB 2 170 1/11/2017 ProductA -8 160 1/12/2017 ProductB -2 180 我希望有一个查询,按照以下方式生成每个工作日的产品总数量:

date A B 1/3/2017 8 0 1/4/2017 8 0 1/5/2017 8 0 1/6/2017 8 0 1/9/2017 8 2 1/10/2017 8 2 1/11/2017 8 2 1/12/2017 0 2 1/13/2017 0 0

2 个答案:

答案 0 :(得分:1)

您需要生成日期并需要对窗口函数进行求和,如下所示:

Declare @startdate date = '2017-01-03'
Declare @enddate date = '2017-01-13'

;with Datescte as (
Select top (datediff(day, @startdate, @enddate) +1) Dt = Dateadd(day, Row_Number() over (order by (Select null))-1, @startdate) 
    from master..spt_values s1, master..spt_values s2
    ), cte2 as (
    Select * from 
        ( Select [Date], Prod_name, Qty from #Dates ) a
        pivot (max(Qty) for prod_name in ([ProductA],[ProductB])) p
    )
    Select Dt as [Date], sum(ProductA) over(order by Dt) as [A], Coalesce(sum(ProductB) over(order by dt),0) as [B]
        from Datescte d
        left join cte2 d2
        on d.dt = d2.Date

首先CTE生成两个日期之间的日期。 第二个CTE确实为两个产品进行了转向,并根据日期列

查询返回总和

答案 1 :(得分:0)

WITH C AS (

SELECT Date,Prod_Name,qty,price FROM YourTable

) 选择 * 来自C.   枢轴(SUM([数量])     FOR Prod_Name IN([ProductA],[ProductB]))AS P;