我有一个如下所示的SQL Server表:
ID | Club Name | Booking Date | Submission Date
---+-------------+-------------------------+-------------------------
1 | Basketball | 2015-10-21 00:00:00.000 | 9/18/2015 3:23:42 PM
2 | Tennis | 2015-10-14 00:00:00.000 | 9/28/2015 1:50:25 PM
3 | Basketball | 2015-10-06 00:00:00.000 | 9/29/2015 11:08:20 AM
1 | Other | 2015-10-21 00:00:00.000 | 9/29/2015 11:08:39 AM
我想知道每个俱乐部在预订日期后不到15天的时间内提交了多少次。
我提出的解决方案是添加一个新列并运行datefiff
函数并将值存储在新列中。然后只按俱乐部名称分组并为>添加参数;新栏目15 ..
我的问题是:这可以在不必创建新列的情况下即时完成吗?如果它在飞行中完成,会影响性能多少?
答案 0 :(得分:4)
是的,这可以在查询中内联完成。在数据库中,您几乎从不想要存储计算列,这就是datediff列的内容。相反,您可以在WHERE子句中进行数学运算。
SELECT
*
FROM
myTable
WHERE
DATEDIFF(day, -15, BookingDate) >= SubmissionDate
我写的很快,所以日期数学可能走错了方向(将来检查而不是过去)但是使用上面的查询会让你走上正确的道路。请记住,如果这个表变得非常大,那么你将会做一个DONIFF的TON,这可能会对性能产生影响。
答案 1 :(得分:1)
这样的东西?
Declare @Table table (Id int,Club_Name varchar(50),Booking_Date datetime,Sumbission_Date datetime)
Insert @Table values
(1,'Basketball','2015-10-21 00:00:00.000','9/18/2015 3:23:42 PM'),
(2,'Tennis ','2015-10-14 00:00:00.000','9/28/2015 1:50:25 PM'),
(3,'Basketball','2015-10-06 00:00:00.000','9/29/2015 11:08:20 AM'),
(1,'Other ','2015-10-21 00:00:00.000','9/29/2015 11:08:39 AM')
Select Club_Name
,Submissions= count(*)
,Early = sum(case when datediff(DD,Sumbission_Date,Booking_Date)<15 then 1 else 0 end)
From @Table
Group By Club_Name
返回
Club_Name Submissions Early
Basketball 2 1
Other 1 0
Tennis 1 0
答案 2 :(得分:0)
试试这个。
SELECT ID,
ClubName,
Sum(Value) As Ttle
FROM
(
SELECT ID,
ClubName,
COUNT(*) AS Value
FROM TableName
GROUP BY ID,
ClubName,
RecordDate
HAVING DATEDIFF(D, BookingDate, SubmissionDate) > 15
) Data
GROUP BY ID,
ClubName,
ORDER BY ttle DESC