选择多个和如何正确按日期过滤

时间:2012-10-11 20:07:28

标签: sql date select sum between

以下是我目前没有通过createdDate过滤任何内容的内容。

SELECT [employeeID]
      ,employeeName
      ,isnull((SELECT SUM(case when clientID != 10 then timeSpent else 0 end)),0) as 'billable'

      ,isnull((SELECT SUM(case when clientID = 10 then timeSpent else 0 end)),0) as 'nonBillable'
FROM [myDB].[dbo].[myTable]
group by employeeID,employeeName

输出:

employeeID employeeName billable nonbillable
---------- ------------ -------- -----------
1          tom          5230     2302
2          dick         25       8439
3          harry        2430     9433

准确的输出会相似但只是在日期范围内的值之和:

employeeID employeeName billable nonbillable
---------- ------------ -------- -----------
1          tom          35       5
2          dick         25       15
3          harry        2        48

[myTable]包含以下字段:employeeID,employeeName,clientID,timeSpent,createdDate

我需要能够在每个select sum语句中添加一个过滤器,类似于以下内容:WHERE createdDate BETWEEN('2012-10-01')AND('2012-10-07')

以下变体都会因SQL错误或输出不准确而失败:

SELECT [employeeID]
      ,employeeName
      ,isnull((SELECT SUM(case when clientID != 10 then timeSpent else 0 end)),0) as 'billable'
      ,isnull((SELECT SUM(case when clientID = 10 then timeSpent else 0 end)),0) as 'nonBillable'
FROM [myDB].[dbo].[myTable]
WHERE createdDate BETWEEN ('2012-10-01') AND ('2012-10-07')
group by employeeID,employeeName

SELECT DISTINCT [employeeID]
      ,employeeName
      ,isnull((SELECT SUM(case when clientID != 10 then timeSpent else 0 end)),0) as 'billable'
      ,isnull((SELECT SUM(case when clientID = 10 then timeSpent else 0 end)),0) as 'nonBillable'
FROM [myDB].[dbo].[myTable]
WHERE createdDate BETWEEN ('2012-10-01') AND ('2012-10-07')
group by employeeID,employeeName

SELECT [employeeID]
      ,employeeName
      ,isnull((SELECT SUM(case when clientID != 10 then timeSpent else 0 end)WHERE createdDate BETWEEN ('2012-10-01') AND ('2012-10-07')),0) as 'billable'
      ,isnull((SELECT SUM(case when clientID = 10 then timeSpent else 0 end)WHERE createdDate BETWEEN ('2012-10-01') AND ('2012-10-07')),0) as 'nonBillable'
FROM [myDB].[dbo].[myTable]
group by employeeID,employeeName,createdDate

非常感谢任何帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

第一个查询应该能为您提供正确的结果

SELECT [employeeID] 
      ,employeeName 
      ,isnull((SELECT SUM(case when clientID != 10 then timeSpent else 0 end)),0) as 'billable' 
      ,isnull((SELECT SUM(case when clientID = 10 then timeSpent else 0 end)),0) as 'nonBillable' 
FROM [myDB].[dbo].[myTable] 
WHERE createdDate BETWEEN '2012-10-01' AND '2012-10-07'
group by employeeID,employeeName 

但是,如果createdDate是日期时间类型,那么它只返回“2012-01-01 00:00”和“2012-10-07 00:00”之间的值 - 2012-10之后没有任何内容-07 00:01理想情况下,您可以将过滤日期指定为日期,而不是字符串。