我曾經有過下面的代碼,以獲得所有「 - 」行動對所有客戶:DistinctCount + LastNonEmpty內OVER子句
with
T1 as
(
select
[Contract] = 'Contract1',
[Customer] = 'Customer4',
[Date] = '2017-01-01',
[Action] = '+'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer6',
[Date] = '2017-01-02',
[Action] = '+'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer4',
[Date] = '2017-01-03',
[Action] = '-'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer4',
[Date] = '2017-01-04',
[Action] = '+'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer4',
[Date] = '2017-01-05',
[Action] = '-'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer6',
[Date] = '2017-01-06',
[Action] = '-'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer8',
[Date] = '2017-01-07',
[Action] = '+'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer8',
[Date] = '2017-01-08',
[Action] = '-'
union all
select
[Contract] = 'Contract1',
[Customer] = 'Customer4',
[Date] = '2017-01-09',
[Action] = '+'
)
select
[Customer],
[Date]
from T1
where [Action] = '-'
現在我需要做的是在合同領域。這意味着當上次操作爲' - '時,必須在該日期之前對所有使用'+'操作的客戶返回合同和日期值。非常期望的輸出應該是:
Date | Contract
------------ | ------
2017-01-06 | Contract1
2017-01-08 | Contract1
預期的算法應該是這樣的:
[PlusDC] = count(distinct iif([Action] = '+',Customer,NULL)) over (partition by [Contract] order by [Date])
[MinusDC] = count(distinct iif([Action] = '-',Customer,NULL)) over (partition by [Contract] order by [Date])
但是:
- 它不反正工作。
- 即使它工作,即使[PlusDC] = [MinusDC],它也會返回值2017-01-09,這是不正確的。
粗略地說,我要檢查以下代碼對所有客戶:
[動作] = ' - ' 當前行。
lag([Action],1)=' - '(或Null,如果客戶記錄在當天晚些時候出現)爲每個客戶。
更新:爲了讓事情更清楚了,我做了我的一列數據爲導向的觀點:
-----------------------------------------------------------------------
| Date | Contract | Customer4 | Customer6 | Customer8 | All |
| ------------ | --------- | --------- | --------- | --------- | --- |
| 2017-01-01 | Contract1 | + | | | |
| 2017-01-02 | Contract1 | | + | | |
| 2017-01-03 | Contract1 | | | | |
| 2017-01-04 | Contract1 | - | | | | <-- Customer6 still has a '+'
| 2017-01-05 | Contract1 | + | | | |
| 2017-01-06 | Contract1 | - | | | | <-- Customer6 still has a '+'
| 2017-01-07 | Contract1 | | - | | - | <-- All customers has '-' or null as a last action
| 2017-01-08 | Contract1 | | | + | |
| 2017-01-09 | Contract1 | | | - | - | <-- All customers has '-' or null as a last action
-----------------------------------------------------------------------
的所有列代表所有客戶的實際狀態(我需要的行)。正如您可能注意到的,2017-01-04和2017-01-06在合同領域內並不是真正的' - '。 Contract1沒有關閉,它仍然有一個Customer6打開。每個合同有一定數量的客戶很容易。無數的事情呢?
有沒有實用的建議?
它應該檢查所有客戶的上次操作(它必須是' - '),按合同分組。請參閱http://pastebin.com/xZvNJ1D1。我已將2017-01-05操作更改爲'+',並且您的代碼仍然返回相同的結果,但不應該,Customer4的最後一個操作是'+',因此它應該不會返回任何結果。 –
你讓我錯了,我已經用視覺重新描述了任務,看到更新的數據。 –
終於,我得到你想要的,檢查我編輯的答案-HTH;)。 –