我有一份我想要制作的报告,显示每年每周的工作数,日期可以追溯到90年代初。我遇到了一个我似乎无法解决的问题,因为我的SQL知识不是很好。
我理解mysql限制你开始星期日或星期一的星期日期。我希望将它们从星期三到星期二分组,所以当我执行GROUP BY YEAR(JOBID), WEEK(JOBID)
时,它只显示从周日开始的几周。
我在这里找到了这个
SELECT
count(jobs) as count,
CASE WHEN (weekday(datetime)<=3) THEN date(datetime + INTERVAL (3-weekday(datetime)) DAY)
ELSE date(datetime + INTERVAL (3+7-weekday(datetime)) DAY)
END as dt
FROM values
但它给了我与
相同的结果集SELECT
COUNT(jobs),
Week(datetime) as Week,
Year(datetime) as Year
FROM jobs
GROUP BY Year(datetime), Week(datetime)
有人可以指出我做错了吗?
答案 0 :(得分:1)
最简单的解决方案是使用日历表。您可以轻松地将星期三作为开始日期定制,而10年的数据仅约为3650行。
http://weblogs.sqlteam.com/dang/archive/2010/07/19/calendar-table-and-datetime-functions.aspx
应该让你开始。
答案 1 :(得分:1)
您的第一个查询不完整,并且不包含“GROUP BY”子句。一定要“GROUP BY”定义“dt”列的相同“CASE”表达式。
您的CASE语句已正确制定,并且只要您的“GROUP BY”子句写得正确,就应该返回您正在寻找的不同结果集。
我已将您的查询重新表述为SQL Server查询,并在我自己的数据上确认它们确实返回了不同的结果集。
以下是所需查询的SQL Server版本:
SELECT
COUNT([jobs]) AS Count,
CASE
WHEN (DATEPART(dw, [datetime])<=3) THEN Convert(date, DATEADD(day, 3-DATEPART(dw, [datetime]), [datetime]))
ELSE Convert(date, DATEADD(day, 3+7-DATEPART(dw, [datetime]), [datetime]))
END AS WeekLabel
FROM JobsTable
GROUP BY
CASE
WHEN (DATEPART(dw, [datetime])<=3) THEN Convert(date, DATEADD(day, 3-DATEPART(dw, [datetime]), [datetime]))
ELSE Convert(date, DATEADD(day, 3+7-DATEPART(dw, [datetime]), [datetime]))
END
ORDER BY
CASE
WHEN (DATEPART(dw, [datetime])<=3) THEN Convert(date, DATEADD(day, 3-DATEPART(dw, [datetime]), [datetime]))
ELSE Convert(date, DATEADD(day, 3+7-DATEPART(dw, [datetime]), [datetime]))
END DESC
您的其他比较查询的SQL Server版本:
SELECT COUNT([jobs]),
DATEPART(week, [datetime]) AS WeekLabel,
DATEPART(year, [datetime]) AS YearLabel
FROM JobsTable
GROUP BY DATEPART(week, [datetime]), DATEPART(year, [datetime])
ORDER BY DATEPART(year, [datetime]) DESC, DATEPART(week, [datetime]) DESC