How to use Condition in oracle count Function

时间:2018-03-23 00:04:20

标签: sql plsql

I have two table Area_Table which has a column name as Area.ID and Defect_table which has a column name as Area.Id, Defect_date.

I need to display Area.ID and "Number of Defects" by a "count of Defect_date" also it should only display dates-

  1. Which are within Last Friday to before Friday in one column
  2. Dates which falls between 4 Fridays.

Sample Table :

    Area_Table -

    Area_ID
    ABC1
    BCD2
    EFG4

Defect_table

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

Required output -

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

Since today is 23/03/2018(Friday) -

Last week Friday range is 09/03/2018 to 16/03/2018. 4 weeks range is 23/03/2018 to 16/03/2018.

My code -

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;

This code shows the wrong output! which is not matching to my required output table above.

2 个答案:

答案 0 :(得分:0)

Use CASE to check if each defect date falls within the 1-week and 4-week range.

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;

答案 1 :(得分:0)

与接受的答案类似,发布此内容很慢:

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