按工作日进行的Sql Server查询,不在午夜开始

时间:2015-06-22 15:21:28

标签: c++ sql-server

我编写了一个查询,用于检查1周内7天的单个行数。 有没有办法重写此查询,以便不必在每个单独的日子输入?我将在c ++应用程序中使用它,该应用程序将在每个星期天下午6点执行一周,然后将所有日期列入文本文件。

select
sum(case when BankDTS BETWEEN '2015-01-11 18:00' AND '2015-01-12 18:00' then 1 else 0 end) as Monday,
sum(case when BankDTS BETWEEN '2015-01-12 18:00' AND '2015-01-13 18:00' then 1 else 0 end) as Tuesday,
sum(case when BankDTS BETWEEN '2015-01-13 18:00' AND '2015-01-14 18:00' then 1 else 0 end) as Wednesday,
sum(case when BankDTS BETWEEN '2015-01-14 18:00' AND '2015-01-15 18:00' then 1 else 0 end) as Thursday,
sum(case when BankDTS BETWEEN '2015-01-15 18:00' AND '2015-06-16 18:00' then 1 else 0 end) as Friday,
sum(case when BankDTS BETWEEN '2015-01-16 18:00' AND '2015-01-17 18:00' then 1 else 0 end) as Saturday,
sum(case when BankDTS BETWEEN '2015-01-17 18:00' AND '2015-01-18 18:00' then 1 else 0 end) as Sunday
FROM BankHistory
Where BankDTS BETWEEN '2015-01-11 18:00' AND '2015-01-18 18:00' AND Type = 'Debit'

编辑:好答案,但我正在改变我的问题,以便从小组中获得结果。问题的背景保持不变。

Select count(*) as B
from BankHistory
where BankDTS BETWEEN '2015-01-19 18:00' AND '2015-01-18 18:00'
group by DATEDIFF(dd, 1, BankDTS)

我想更改我的DateDiff,例如每天2015-01-19 18:00到2015-01-20 18:00显示为1天。

3 个答案:

答案 0 :(得分:4)

您可以使用datepart函数查找星期几。您可以使用日期添加功能来转移时间。

select
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=2 then 1 else 0 end) as Monday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=3 then 1 else 0 end) as Tuesday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=4 then 1 else 0 end) as Wednesday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=5 then 1 else 0 end) as Thursday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=6 then 1 else 0 end) as Friday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=7 then 1 else 0 end) as Saturday,
sum(CASE WHEN DATEPART(DW,DATEADD(HOUR, 6, BankDTS ))=1 then 1 else 0 end) as Sunday
FROM BankHistory
Where BankDTS BETWEEN '2015-01-11 18:00' AND '2015-01-18 18:00'

要进行更改以便将每天报告为一行,它将如下所示:

Select DATEADD(HOUR, 6, BankDTS ) Date,
    DATEPART(DW,DATEADD(HOUR, 6, BankDTS )) Weekday,
    count(*) as B
from BankHistory
Where BankDTS BETWEEN '2015-01-11 18:00' AND '2015-01-18 18:00'
group by DATEADD(HOUR, 6, BankDTS )
order by DATEADD(HOUR, 6, BankDTS )

答案 1 :(得分:0)

由于您使用时间组件,这有点棘手,但您可以使用DATEDIFF和DATEPART来确定结束日期(或开始日期)的偏移量。

因此,您的案例将在DATEDIFF提供的秒数(或分钟)范围内使用,而不是日期本身。

答案 2 :(得分:0)

您可以使用以下内容:

SELECT DATEADD (hh , 18 , DATEADD(dd, 0, DATEDIFF(dd, 1, GETDATE())) ) AS YesterdayAt6PM, DATEADD (hh , 18 , DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) ) AS TodayAt6PM

您可以按照自己的方式调整上一个查询。此外,尽可能防止重复计算。例如,您可以将GETDATE()放在单独的变量中。