我有一张访客表。 访客具有以下列:
编号
StartTime (日期)
已购买(bool)
发货(bool)
对于过去7天内的每一天,我想选择3位当天访客 StartTime :
理想情况下,返回的结果是:
Day Total TotalPurchased TotalShipped
1 100 67 42
2 82 61 27
etc...
我已经习惯了.NET Linq,所以这对我来说是一个很大的挑战。
到目前为止我提出的所有内容如下:
SELECT COUNT(*) AS Total
FROM [dbo].[Visitors]
WHERE DAY([StartTime]) = DAY(GETDATE())
它选择当天的总数就好了,不过我现在感觉很困难,所以如果有人能指出我正确的方向,它会很好。
答案 0 :(得分:1)
过去7天使用Stanislav提出的查询,但使用此WHERE
条款
SELECT DAY([StartTime]) theDay,
COUNT(*) AS Tot,
SUM(CASE WHEN Purchased=true THEN 1 ELSE 0 END) as TotPurch,
SUM(CASE WHEN Shipped=true THEN 1 ELSE 0 END) as TotShip
FROM [dbo].[Visitors]
WHERE [StartTime] BETWEEN GETDATE()-7 AND GETDATE()
GROUP BY DAY([StartTime])
答案 1 :(得分:0)
SELECT COUNT(*) AS Total,
SUM(CASE WHEN Purchased=true THEN 1 ELSE 0 END) as TotalPurchased,
SUM(CASE WHEN Shipped=true THEN 1 ELSE 0 END) as TotalShipped
FROM [dbo].[Visitors]
WHERE DAY([StartTime]) = DAY(GETDATE())
并按照jarlh提到的那样添加GROUP BY DAY([StartTime])
答案 2 :(得分:0)
这是一个简单的选择,可以为您提供所需的数据集
SELECT DATEDIFF(day,StartTime, getdate())+1 as [Day], -- Add 1 to display 1 to 7 instead of 0 to 6
COUNT(*) as Total,
SUM(CASE WHEN Purchased = 1 THEN 1 ELSE 0 END) as TotalPurchased,
SUM(CASE WHEN Shipped = 1 THEN 1 ELSE 0 END) AS TotalShipped
FROM Visitors
WHERE DATEDIFF(day,startTime,GETDATE()) < 6
GROUP BY DATEDIFF(day,startTime,GETDATE())
ORDER BY 1
此查询不会考虑日期的时间部分。
答案 3 :(得分:0)
由于该表在[dbo]中,这可能与Sql Server数据库有关。
在这种情况下,[已购买]和[已发货]列很可能是BIT字段。
此类BIT字段可以使用SUM和IIF或CASE WHEN计算 并且DATEDIFF可用于选择之前的7天。
SELECT
DAY([StartTime]) as [Day],
SUM(IIF([Purchased] = 1, 1, 0)) AS TotalPurchased,
SUM(case when [Shipped] = 1 then 1 else 0 end) AS TotalShipped,
COUNT(*) AS Total
FROM [dbo].[Visitors]
WHERE datediff(day, [StartTime], GETDATE()) BETWEEN 1 AND 7
GROUP BY DAY([StartTime])
ORDER BY 1;
如果该表在日期字段上编入索引,则此WHERE子句应该更快地产生结果:
WHERE [StartTime] between dateadd(day,-7,cast(GETDATE() as date)) and dateadd(day,-1,cast(GETDATE() as date))