Where子句中的Case语句

时间:2014-01-02 18:29:09

标签: sql case

我正在尝试重写以下查询,以便为本周而非当天提供最佳表现。因为我的星期一是星期五到星期日,所以我需要告诉sql,如果日期是x,那么它所在的星期是y。

这是我每天的工作查询:

SELECT u.UserName, COUNT t.Policy AS Policies, SUM t.Fee AS Premium
FROM Users u INNER JOIN PolicyInfo t ON u.UserID = t.UserID
WHERE t.Date >= convert(date,getdate()))
GROUP BY u.UserName
ORDER BY Policies desc, Premium desc

这是我的非工作周刊查询:

SELECT u.UserName, COUNT t.Policy AS Policies, SUM t.Fee AS Premium
FROM Users u INNER JOIN PolicyInfo t ON u.UserID = t.UserID
WHERE t.Date >= convert(date,getdate()))
AND CASE DATEPART(WEEKDAY, t.Date)
    WHEN 1 THEN cast (convert(varchar (8), DATEADD(d,5,[t.Date]),112) as date)
    WHEN 2 THEN cast (convert(varchar (8), DATEADD(d,4,[t.Date]),112) as date)
    WHEN 3 THEN cast (convert(varchar (8), DATEADD(d,3,[t.Date]),112) as date)
    WHEN 4 THEN cast (convert(varchar (8), DATEADD(d,2,[t.Date]),112) as date)
    WHEN 5 THEN cast (convert(varchar (8), DATEADD(d,1,[t.Date]),112) as date)
    WHEN 6 THEN cast (convert(varchar (8), DATEADD(d,0,[t.Date]),112) as date)
    WHEN 7 THEN cast (convert(varchar (8), DATEADD(d,6,[t.Date]),112) as date)

GROUP BY u.UserName
ORDER BY Policies desc, Premium desc

1 个答案:

答案 0 :(得分:0)

获得当周第一天的简单计算是:

SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP)

由于您需要确定最近的星期五,因此需要进行一些调整:

SELECT DATEADD(DAY, (12-DATEPART(WEEKDAY, CURRENT_TIMESTAMP) % 7) - 6, CURRENT_TIMESTAMP)

现在你有了这个,你可以将它添加到GROUP BY子句:

SELECT u.UserName, t.weekStarting, COUNT(t.Policy) AS Policies, SUM(t.Fee) AS Premium
FROM Users u 
INNER JOIN (
  SELECT *, SELECT DATEADD(DAY, (12-DATEPART(WEEKDAY, Date) % 7) - 6, Date) weekStarting
  FROM PolicyInfo) t ON u.UserID = t.UserID
WHERE t.Date >= convert(date,getdate())
GROUP BY u.UserName, t.weekStarting
ORDER BY Policies desc, Premium desc