如何排除当前周中的SQL数据

时间:2017-07-17 04:38:26

标签: sql sql-server

目前我有一些SQL效果很好,除了我不断删除结果的第一行,因为它只包含(此时是星期一17日)数据的部分时间,并且被分组在这个领域,它显示'假数据'

以下是当前代码:

SELECT
    YEAR(submitted)  YEAR,
    COUNT(request)   Total_Requests,
    DATEPART( wk, submitted) WEEK
FROM
    wv_external_statistics
WHERE
    userid <> 'anonymous'
GROUP BY
    YEAR(submitted),
    DATEPART( wk, submitted)

以下是一些示例数据:

YEAR | Total_Requests | WEEK
2017 |      361       | 28
2017 |     2486       | 27
2017 |     2860       | 26
2017 |     4521       | 25
2016 |     2600       | 52
2016 |     3028       | 51
....

正如您所看到的那一行是当前的一周,因为我们只是在一周的第一天数据未完成,所以我想从结果中排除这一行...我刚试过下面,立即找到零行,所以我显然做了一些愚蠢的事情,我希望有人可以指出这一点?

DATEPART( wk, submitted) <= DATEPART( wk, submitted)-1

注意:我需要保留2016年的所有数据,即使它的周数大于本周,也就是前几年的年份。 干杯

3 个答案:

答案 0 :(得分:2)

如果要删除当前周。为什么不把它扔在where子句......

其中 Datepart(wk,已提交)!= datepart(wk,getdate())

答案 1 :(得分:2)

SELECT YEAR(SubmittedDate) As [YEAR]
    ,COUNT(Request) As Total_Requests
    ,DATEPART(WEEK, SubmittedDate) As [WEEK]
FROM wv_external_statistics
WHERE UserID <> 'Anonymous' Or ((DATEPART(WEEK, SubmittedDate) - 
DATEPART(WEEK, GETDATE()) = 0) And (YEAR(SubmittedDate) - YEAR(GETDATE()) = 0))
GROUP BY YEAR(SubmittedDate),DATEPART(WEEK, SubmittedDate);

答案 2 :(得分:1)

你需要指定条件(好吧,应该承认它长,模糊,可能不是最佳)

SELECT
    YEAR(submitted)  YEAR,
    COUNT(request)   Total_Requests,
   DATEPART( wk, submitted) WEEK
FROM
    wv_external_statistics
WHERE
    userid <> 'anonymous'
GROUP BY
    YEAR(submitted),
    DATEPART( wk, submitted)
    having year(submitted) * 100 + datepart(wk, submitted) < (select max(year(submitted) * 100 + datepart(wk, submitted)) from wv_external_statistics)

因为您的条件(DATEPART( wk, submitted) <= DATEPART( wk, submitted)-1)对于查询中的每一行始终为false