查询每周报告

时间:2011-06-08 14:52:32

标签: sql-server tsql

我目前正在编写一个查询,以生成每周一至下周日的每周报告。

SELECT top 10 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday, count(items)
FROM myitemtable
GROUP BY 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday    

VS

SELECT count(items)
FROM myitemtable
WHERE mydatefield >= '2011/05/30 00.00.000' and mydatefield <= '2011/06/05 23.59.59' 

上述查询有什么问题。计数在第一个和第二个查询中加起来不同。

1 个答案:

答案 0 :(得分:1)

如果没有特别理解查询(因为我通常使用比tsql更常用的SQL标准版本来编写),在查看查询时我的直觉反应是这可能是一个时区问题。但是,您需要做的是验证您获得的答案是否符合您的期望。为此,请运行:

SELECT mydatefield,
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday
FROM myitemtable
WHERE mydatefield >= '2011/05/30 00.00.000' and mydatefield <= '2011/06/05 23.59.59'

如果这是太多的数据,这是另一种选择:

SELECT min(mydatefield),max(mydatefield),count(*),
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday
FROM myitemtable
WHERE mydatefield >= '2011/05/30 00.00.000' and mydatefield <= '2011/06/05 23.59.59'
GROUP BY 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday

和相关:

SELECT min(mydatefield),max(mydatefield),count(*),
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday
FROM myitemtable
GROUP BY 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield), '19000101') as EveryMonday, 
 DATEADD(WEEK, DATEDIFF(WEEK, '19000101', mydatefield)+1, '19000101')-1 as EverySunday

运行这些查询可以帮助您了解“EveryMonday”和“EverySunday”查询是否生成了您期望的值。查看最小/最大日期将有助于您了解何时发生不匹配。