我有一个名为“事故”的表。我想根据报告日期所在的季度返回所有记录。 表格的外观如下:
Accidents Table
| acc_id | acc_descrip |reported_date|
| 1 | collision |2019-20-01
| 2 | hit and run |2019-08-01
| 3 | collision |2019-10-06
所以这可以为我提供表中的所有记录以及它们属于哪个季度和年份。但是我只想传递参数year并获得该记录的年份和该季度的结果掉进去?
alter PROCEDURE AccidentByQuarter
AS
BEGIN
SELECT *,
CASE
WHEN MONTH(ReportedDate) IN (1,2,3) THEN convert(char(4), YEAR(ReportedDate) - 1) + 'Q3'
WHEN MONTH(ReportedDate) IN (4,5,6) THEN convert(char(4), YEAR(ReportedDate) - 1) + 'Q4'
WHEN MONTH(ReportedDate) IN (7,8,9) THEN convert(char(4), YEAR(ReportedDate) - 0) + 'Q1'
WHEN MONTH(ReportedDate) IN (10,11,12) THEN convert(char(4), YEAR(ReportedDate) - 0) + 'Q2'
END AS Quarter FROM Incident
END
答案 0 :(得分:0)
如果性能不是大问题,我会这样做:
alter procedure AccidentByMonth (
@ReportedDate int
)
AS
Begin
select *
from Incident
where month(ReportedDate) / 4 = @ReportedDate / 4
End;
有点奥秘-因为值从1而不是0开始。这样做可能更易读:
where (month(ReportedDate) - 1) / 4 = (@ReportedDate - 1) / 4
或者:
where datepart(quarter, RepertedDate) = (@ReportedDate - 1) / 4
答案 1 :(得分:0)
这是另一种可能的解决方案。
此查询为给定的@ReportedDate
参数动态计算季度开始和结束的日期。因此,它将利用列ReportedDate
上的索引,因为在比较运算符的左侧不会进行任何计算。
ALTER PROCEDURE AccidentByMonth (@ReportedDate int)
AS
BEGIN
SELECT *
FROM Incident
WHERE
ReportedDate >= DATEADD(q, DATEDIFF(q, 0, @ReportedDate), 0)
AND ReportedDate < DATEADD(d, -1, DATEADD(q, DATEDIFF(q, 0, @ReportedDate) + 1, 0))
END
答案 2 :(得分:0)
您应该尝试一下。根据您的参数名称@ReportDate,我假设该日期为整数(20190207 = 2019-02-07)。我使用CONVERT函数,因为您的函数参数是INT。
02-07 16:30:11.371 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:33:10.831 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.611 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.631 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.651 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.661 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.671 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.681 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.701 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.711 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.731 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:38:49.751 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:40:50.041 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:43:55.861 3763-3818/cu.uci.cegel.quejas E/Work manager: Sync
02-07 16:45:11.441 3763-3789/cu.uci.cegel.quejas E/Work manager: Sync