簡體   English   中英

如何在oracle count函數中使用條件

[英]How to use Condition in oracle count Function

我有兩個表Area_Table ,其列名稱為Area.ID, Defect_table ,其列名稱為Area.Id,Defect_date。

我需要通過“ Area.ID數量”顯示Area.ID和“缺陷數量”,並且它應該僅顯示日期-

  1. 在一列中位於上周五至周五之前
  2. 日期介於4個星期五之間。

樣品表:

    Area_Table -

    Area_ID
    ABC1
    BCD2
    EFG4

缺陷表

Area_Id      Defect_date
ABC1         13/03/2018
ABC1         11/03/2018
EFG4         08/03/2018

所需的輸出-

Area_id    Count of 1 week     Count of 4week
ABC1              2                    2
BCD2              0                    0
EFG4              0                    1

從今天起23/03/2018(星期五)-

上周星期五的范圍是2018年9月3日至2018年3月16日。 4周的范圍是23/03/2018至16/03/2018。

我的代碼-

Select A.Area_Id, D.Defect_date, 
count((next_day(trunc(sysdate, 'iw'), 'Friday') - 14-(next_day(trunc(sysdate, 'iw'), 'Friday') -  7)) as "Count of 1 week", 
count((next_day(trunc(sysdate, 'iw'), 'Friday') - 28 -(next_day(trunc(sysdate, 'iw'), 'Friday') -  7)) as "Count of 4 week" 
From Area_table A inner join Defect_date D on A.Area_ID = D.Area_ID
Group by A.Area_Id, D.Defect_date;

此代碼顯示錯誤的輸出! 與我上面要求的輸出表不匹配。

使用CASE檢查每個缺陷日期是否在1周和4周范圍內。

Select A.Area_Id,  
sum( case when defect_date between (next_day(trunc(sysdate, 'iw'), 'Friday') -  14) and 
                              (next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 
     end ) as "Count of 1 week",
sum( case when defect_date between (next_day(trunc(sysdate, 'iw'), 'Friday') -  35) and 
                              (next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 
     end ) as "Count of 4 week"
From Area_table A left join Defect_date D on A.Area_ID = D.Area_ID
Group by A.Area_Id;

類似於已接受的答案,但發布速度較慢:

Select A.Area_Id, 
sum(case when D.Defect_date between
next_day(trunc(sysdate-2*7, 'iw'), 'Friday')  and 
next_day(trunc(sysdate-7, 'iw')  , 'Friday')  then 1 else 0 end)  as "Count of 1 week",
sum(case when D.Defect_date between
next_day(trunc(sysdate-5*7, 'iw'), 'Friday')  and 
next_day(trunc(sysdate-7, 'iw')  , 'Friday')  then 1 else 0 end)  as "Count of 4 weeks"
From Area_table A left join Defect_date D on A.Area_ID = D.Area_ID
Group by A.Area_Id
Order by A.Area_Id;

Result:

AREA_ID Count of 1 week Count of 4 weeks
ABC1    2               2
BCD2    0               0
EFG4    0               1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM