2017-01-03 28 views
0

我有兩個表,employeeemployee time entry。我運行了一個查詢,向我顯示所有員工輸入的時間總和或0作爲空值。在下一列中我有周編號。如果員工在一週內沒有輸入時間,那麼它在給予我0的時候也沒有輸入時間,但是它也在我的週數中給出了空值。假設沒有員工進入,我怎麼能強制查詢顯示我的週數。SQL根據查詢顯示空值的日期

Select 
    Concat(Empfname,Emplname) as EmployeeName, 
    department, 
    iif (sum(whours) is null, 0, sum(whours)) CurrentHours, 
    Datepart (ww,wdate) WeekNum 
From 
    employee as e 
left outer join 
    TimeEntry as w on e.id = w.eId 
        and wdate between '01/01/2017' and '01/31/2017' 
group by 
    Concat(Empfname,Emplname), department, Datepart(ww, wdate) 

輸出

EmployeeName Department CurrentHours WeekNum 
------------------------------------------------ 
John Smith  Sales  8   1 
Smith John  Operations 0   Null 

我怎麼能告訴它也是從WEEKNUM 1?

感謝

+0

如果員工沒有及時進入,您怎麼知道它屬於第1周? – GurV

+0

如果沒有參賽作品,您希望顯示幾周的數字? – Mureinik

+0

你可以使用'coalesce(Datepart(ww,wdate),1)',如果你希望它成爲1,那麼它會變爲null – GurV

回答

0

試試這個:

Select Concat(Empfname,Emplname) as EmployeeName, department 
iif (sum(whours) is null, 0, sum(whours)) CurrentHours 
ISNULL(Datepart (ww,wdate),1) WeekNum 

From employee as e left outer join TimeEntry as w on e.id=w.eId 
and wdate between '01/01/2017' and '01/31/2017' 

group by Concat(Empfname,Emplname), department, ISNULL(Datepart (ww,wdate),1) 

這將迫使任何NULL值顯示的1代替NULL本身

+0

這將在第1周很好地工作。那麼我什麼時候去第20周?那麼這可能不起作用。 – Invisible

+0

但是你怎麼知道哪個'NULL'對應哪個星期? – LONG

+0

這就是爲什麼我也很困惑。我正在準備每週報告並查看哪些員工未進入他們的工作時間。希望有人也遇到了這個問題,並可能能夠解決這個問題。 – Invisible

1

的想法是使用cross join產生的所有行,然後使用left join來引入你想要的東西像這樣的行:

Select Concat(e.Empfname, e.Emplname) as EmployeeName, e.department, 
     coalesce(sum(whours), 0) as CurrentHours 
     datepart(week, wd.wdate) as WeekNum 
from employee e cross join 
    (select distinct wdate from TimeEntry) wd left outer join 
    TimeEntry tw 
    on e.id = w.eId and tw.wdate = wd.wdate 
where wd.wdate between '2017-01-01' and '2017-01-31' 
group by Concat(e.Empfname, e.Emplname), e.department, Datepart(week, wd.wdate); 
+0

這隻顯示已輸入時間的員工。我想要員工表中的所有活動員工。表中還有不活躍的員工。 – Invisible

+0

@Invisible。 。 。這應該顯示*所有*員工。 「交叉加入」基於所有員工,沒有其他過濾。 –