用于获取给定日期范围的总计的SQL语句

时间:2013-07-22 15:58:51

标签: sql sql-server tsql

我想在给定的日期范围内每天按日期获取预订数量及其总价值。

我的表格如下:

BookingId (int)
BookingFare (decimal)
BookingDateTime (datetime)

我只能使用以下方法将BookingDateTime转换为日期:

SELECT CONVERT(varchar(8), BookingDateTime, 112) as BookingDateOnly
FROM   [TaxiBookingOnline].[dbo].[Bookings]

我所追求的是这样的:

Date         Bookings   Value
2013-07-10   10         256.24
2013-07-11   12         321.44
2013-07-12   14         311.53

我觉得我应该对表格进行别名,将其加入到自身然后使用“GROUP BY”但我无法使其工作。

非常感谢任何帮助。

感谢。

4 个答案:

答案 0 :(得分:2)

怎么样

select
   cast(BookingDateTime as date) [Date],
   count(*) [Bookings],
   sum(BookingFare) [Value]
from t
group by cast(BookingDateTime as date)

答案 1 :(得分:1)

SELECT   CONVERT(VARCHAR(8), BookingsDateTime, 112) AS [Date],
         COUNT(*)  AS [Bookings],
         SUM(BookingsFare AS [Value]
FROM     MyTable
GROUP BY DATEADD(dd, 0, DATEDIFF(dd, 0, BookingDateTime))

SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, dateColumn))分组,有效获取datetime的日期部分,然后您可以根据需要对分组值使用countsum

编辑:如果您使用的是SQL Server> = 2008,则可以转换为date(就像@AlexK已经完成的那样),否则您必须使用DATEADD进行攻击。

答案 2 :(得分:0)

以下是代码。将Date1和Date2替换为日期范围值:

SELECT 
CONVERT(varchar(8), BookingDateTime, 112) as BookingDateOnly, BookingID   Bookings,Sum(BookingFare)Value  
FROM 
[TaxiBookingOnline].[dbo].[Bookings]
WHERE BookingDateTime Between 'Date1' and 'Date2'
GROUP BY
BookingDateTime,BookingID

答案 3 :(得分:0)

SELECT
    CONVERT(DATE,BookingDateTime) BookingDate,
    COUNT(BookingID) Bookings,
    SUM(BookingFare) BookingFare
FROM TaxiBookingOnline.dbo.Bookings