我需要帮助来根据时间范围计算金额。另外,需要拿出整个月的计算结果。这是根据入住日期进行的轮班交易计算。
例如: 班次01/05/2019开始于8:00:00,结束于02/05/2019 07:59:59 这是我的sql
Select CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120) Date,
SUM(P.Amount - B.TourismTaxAmount) Amount
From Bookings B
Inner Join BookingPayments BP On B.ID = BP.BookingID
Inner Join Payments P On P.ID = BP.PaymentID
Where BookingStatus IN (2,3,4,6) and
IsNull(CheckInDate, DateCheckIn) >= '2019-05-01 08:00:00' and
IsNull(CheckInDate, DateCheckIn) <= '2019-05-02 07:59:59'
group by CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120)
order by CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120)
以下是输出:
-------------------------
| Date | Amount |
-------------------------
| 2019-05-01 | 123.00 |
| 2019-05-02 | 456.00 |
-------------------------
此SQL已经是正确的。。但是我如何使输出如下:
-------------------------
| Date | Amount |
-------------------------
| 2019-05-01 | 579.00 |
-------------------------
并且从上面..我需要按日期生成月度班次摘要并输出如下:
-------------------------
| Date | Amount |
-------------------------
| 2019-05-01 | 579.00 |
| 2019-05-02 | 891.00 |
| 2019-05-03 | 721.00 |
| .......... | ..... |
| .......... | ..... |
-------------------------
感谢您的帮助和解决方案。 谢谢
答案 0 :(得分:2)
按日期顺序使用窗口函数sum()
Select CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120) Date,
SUM(P.Amount - B.TourismTaxAmount) over(order by CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120)) Amount
From Bookings B
Inner Join BookingPayments BP On B.ID = BP.BookingID
Inner Join Payments P On P.ID = BP.PaymentID
Where BookingStatus IN (2,3,4,6) and
IsNull(CheckInDate, DateCheckIn) >= '2019-05-01 08:00:00' and
IsNull(CheckInDate, DateCheckIn) <= '2019-05-02 07:59:59'
order by CONVERT(char(10), IsNull(CheckInDate, DateCheckIn), 120)
答案 1 :(得分:1)
对于Sql-Server,我首先创建一个SQL,使用
以正确的格式显示Date-Column。Select Year(myDate)*10000+Month(myDate)*100+Day(myDate) as MyNewDate ...
然后,如果您通过WITH在CTE中使用查询,则更容易对其进行分组。
答案 2 :(得分:1)
只需减去8小时即可进行汇总。您可以通过所需的日期表达式轻松定义变量(井,列),从而得到:
Select convert(char(10), v.dte, 120) as Date,
sum(P.Amount - B.TourismTaxAmount) as Amount
From Bookings B Inner Join
BookingPayments BP
On B.ID = BP.BookingID Inner Join
Payments P
On P.ID = BP.PaymentID cross apply
(values (convert(date, dateadd(hour, -8, coalesce(CheckInDate, DateCheckIn))))
) v(dte)
Where BookingStatus in (2, 3, 4, 6) and
v.dte >= '2019-05-01' and
v.dte < '2019-05-02'
group by v.dte
order by v.dte;
这也很容易扩展到多个日期或月份。