我的salesOrderheader表中有Shipdate和Totaldue列。
我当前的查询是这样的
select
[ShipDate], SUM([TotalDue]) Total
from
Sales.SalesOrderHeader
where
[ShipDate] between '2005-08-1' and '2005-08-31'
group by
[ShipDate]
这会返回每天总销售额的结果,我想要一个结果,其中每个日期列对应一个显示当月销售的值(即此处的totaldue)。就像2005-08-1的到期总额为1000美元一样,2005-08-2的到期总额为3000美元,2005-08-3的总额为6000美元,那么结果应该是,
ShipDate MTD Value
-----------------------
2005-08-1 1000
2005-08-2 4000
2005-08-3 11000
依此类推,直到2008-08-31。我是数据库的新手,似乎无法解决这个问题。如果有人知道怎么做,请帮助我。感谢
答案 0 :(得分:0)
你可以这样做:
select soh1.ShipDate, SUM(soh2.TotalDue) from
(select distinct ShipDate from sales.SalesOrderHeader
where ShipDate < '2005-09-01' and ShipDate >= '2005-08-01') as soh1
join sales.SalesOrderHeader soh2
on soh2.ShipDate <= soh1.ShipDate and soh2.ShipDate >= '2005-08-01'
group by soh1.ShipDate order by soh1.ShipDate
联接将创建以下结果集:
和Sum和Group By将日期连接起来。
答案 1 :(得分:0)
这可以很好地运作并且表现得相当不错:
;with soh as (
select ShipDate, sum(TotalDue) as TotalDue
from Sales.SalesOrderHeader
where ShipDate between '20050801' and '20050831'
group by ShipDate
)
select ShipDate, sum(TotalDue) over(order by ShipDate) as Total
from soh