Sql销售报告

时间:2014-10-15 14:53:44

标签: sql

我正在尝试为销售做一份报告。这是我到目前为止所做的,但我需要把它分解成商店。 storeid的orders表中有一个字段。我想返回每个商店的总数。有人能指出我正确的方向吗?

select DAY(d.date) as Day, MONTH(d.date) as Month, YEAR(d.date) as year, isnull(t.amnt, 0) as [Total Sales] from (
    SELECT
    sum(o.OrderTotal) amnt,
            DAY(o.OrderDate) as 'Day', 
            YEAR(o.OrderDate) as 'Year', 
        MONTH(o.OrderDate) as 'Month'
            FROM [Orders] o
            where  
    o.OrderDate  > @StartDate + ' 00:00:00' and o.OrderDate  < '' + @EndDate + ' 23:59:59'
    group by YEAR(o.OrderDate), Month(o.OrderDate), DAY(o.OrderDate)
) t
right join (
    select dateadd(dd, -number, getdate()) as date
    from master.dbo.spt_values 
    where type = 'p' and number < DATEDIFF(d, @StartDate, @EndDate) +1

) d  on year(d.date) = t.[year] and month(d.date) = t.[month] and day(d.date) = t.[day]
order by YEAR(d.date), MONTH(d.date), DAY(d.date)

1 个答案:

答案 0 :(得分:0)

将storeId添加到GROUP BY子句和SELECT子句。

select DAY(d.date) as Day, MONTH(d.date) as Month, YEAR(d.date) as year, isnull(t.amnt, 0) as [Total Sales], o.storeId from (
    SELECT
    sum(o.OrderTotal) amnt,
            DAY(o.OrderDate) as 'Day', 
            YEAR(o.OrderDate) as 'Year', 
        MONTH(o.OrderDate) as 'Month'
            FROM [Orders] o
            where  
    o.OrderDate  > @StartDate + ' 00:00:00' and o.OrderDate  < '' + @EndDate + ' 23:59:59'
    group by YEAR(o.OrderDate), Month(o.OrderDate), DAY(o.OrderDate), o.storeId
) t
right join (
    select dateadd(dd, -number, getdate()) as date
    from master.dbo.spt_values 
    where type = 'p' and number < DATEDIFF(d, @StartDate, @EndDate) +1

) d  on year(d.date) = t.[year] and month(d.date) = t.[month] and day(d.date) = t.[day]
order by YEAR(d.date), MONTH(d.date), DAY(d.date)