2016-06-09 46 views
1

我想計算符合某些條件的記錄,條件是從行中具有很大差異的特定值導出的。計數記錄符合SQL中的多個和變量條件,如countifs

下表是50K +記錄表的摘錄;

BatchNumber  | Number | LabId | StateId | Week | OccurrenceId 
----------------+----------+-------+---------+---------+------------- 
101347-1M-37 | 101347 | 1 | 100 | 201610 |  
101347-1-1546L | 101347 | 1 | 100 | 201611 |  
101347-1M-41 | 101347 | 1 | 100 | 201614 |  
101347-1M-1545 | 101347 | 1 | 100 | 201618 |  
101347-1-37  | 101347 | 1 | 101 | 201607 |  
101347-1-1541 | 101347 | 1 | 101 | 201611 |  
101347-1M-37 | 101347 | 1 | 101 | 201616 |  
101347-1-1546L | 101347 | 1 | 101 | 201617 |  
101347-1M-41 | 101347 | 1 | 101 | 201620 |  

我想在Excel中countifs功能很像你能指望一個記錄的發生。

sum()count()函數結合case聲明不會做伎倆我認爲,因爲標準根據行中的值不同。

我已經在聲明中得到什麼occurrenceId到目前爲止是這樣的:

sum(case when v.number = v.number 
      and b.LabId = b.LabId 
      and po.StateId = po.StateId 
      and po.Week < po.Week 
     then 1 
     else 0 
    end) as occurenceid 

此語句會導致0爲每個記錄。

但是省略了and po.Week < po.Week部分返回這個(這對我來說我不明白,但它似乎在某處);

BatchNumber  | Number | LabId | StateId | Week | OccurrenceId 
----------------+----------+-------+---------+---------+------------- 
101347-1M-37 | 101347 | 1 | 100 | 201610 | 1 
101347-1-1546L | 101347 | 1 | 100 | 201611 | 1 
101347-1M-41 | 101347 | 1 | 100 | 201614 | 1 
101347-1M-1545 | 101347 | 1 | 100 | 201618 | 1 
101347-1-37  | 101347 | 1 | 101 | 201607 | 5 
101347-1-1541 | 101347 | 1 | 101 | 201611 | 2 
101347-1M-37 | 101347 | 1 | 101 | 201616 | 4 
101347-1-1546L | 101347 | 1 | 101 | 201617 | 1 
101347-1M-41 | 101347 | 1 | 101 | 201620 | 1 

我不能簡單地寫v.number = 101347 and b.LabId = 1 and po.StateId = 100因爲我需要所有的統計記錄和許多不同的號碼,LabIds,StateIds等應用。

只是爲了清楚起見,我需要達到的效果是這樣的:

BatchNumber  | Number | LabId | StateId | Week | OccurrenceId 
----------------+----------+-------+---------+---------+------------- 
101347-1M-37 | 101347 | 1 | 100 | 201610 | 1 
101347-1-1546L | 101347 | 1 | 100 | 201611 | 2 
101347-1M-41 | 101347 | 1 | 100 | 201614 | 3 
101347-1M-1545 | 101347 | 1 | 100 | 201618 | 4 
101347-1-37  | 101347 | 1 | 101 | 201607 | 1 
101347-1-1541 | 101347 | 1 | 101 | 201611 | 2 
101347-1M-37 | 101347 | 1 | 101 | 201616 | 3 
101347-1-1546L | 101347 | 1 | 101 | 201617 | 4 
101347-1M-41 | 101347 | 1 | 101 | 201620 | 5 

回答

0

明白了!使用具有多個內部連接條件的子查詢。

select v.Number, b.LabId, po.StateId, po.Week, count(sub.Week) as occurrenceid 

from Batch b 

inner join ProductionOrder po on po.BatchId = b.BatchId 
inner join Variety v on b.VarietyId = v.VarietyId 
inner join 
    (select v.Number, b.LabId, po.StateId, po.Week 

    from Batch b 

    inner join ProductionOrder po on po.BatchId = b.BatchId 
    inner join Variety v on b.VarietyId = v.VarietyId 

    ) sub on v.number = sub.Number and b.LabId = sub.LabId and po.StateId = sub.StateId and po.Week >= sub.Week 

where v.Number = 101347 and po.StateId > 99 

group by v.Number, b.LabId, po.StateId, po.Week 

它可能不是最優雅的解決方案,所以仍然渴望看到更好的答案。

相關問題