2012-10-11 64 views
1

這是我目前沒有過濾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]具有以下字段:僱員, employeeName,clientID,timeSpent,createdDate

我需要能夠添加過濾器到eac h選擇總和語句與以下內容類似: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 

任何幫助將不勝感激。

在此先感謝。

+0

你應該指定SQL平臺 - 這看起來像SQL Server? – podiluska

回答

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-2015之間的返回值10-07 00:00' - 2012-10-07 00:01以後沒事了。理想情況下,您可以將過濾日期指定爲日期,而不是字符串。

+0

你是對的。當我在發佈問題之前運行它時,我一定有些微不同。謝謝。 –