将条件子句(Where)添加到密集排名函数

she*_*020 2 sql sql-server dense-rank ranking-functions

我想创建一个排名函数来计算一个人访问财产的次​​数BY DATE,但条件是不包含访问类别。'Calls'

DENSE_RANK() over(partition by activitytable.[Property] 
ORDER BY activitytable.[Date] as Job rank
Run Code Online (Sandbox Code Playgroud)

这样做对我不想要的整个通信表进行排名。

活动ID 财产 日期 通讯类型
1046 红色地产 2019年10月30日 场地 2
10467 红色地产 2019年10月29日 场地 1
10591 红色地产 2019年10月28日 通话
10971 蓝色地产 2019年10月27日 场地 2
10971 蓝色地产 2019年10月26日 场地 1
10971 蓝色地产 2019年10月26日 来电
10965 绿色地产 2019年10月24日 来电
10765 绿色地产 2019年10月23日 来电
10765 绿色地产 2019年10月19日 场地 3
10765 绿色地产 2019年10月15日 场地 2
10765 绿色地产 2019年10月12日 场地 1

理想情况下,我希望表格像上面一样显示,以忽略通信类型列的呼叫元素并仅计数字段类别。我怎么能这样做呢?

Zho*_*rov 5

您需要按Property和进行分区CommunicationType

桌子:

CREATE TABLE #Data (
    ActivityID int,
    Property varchar(100),
    [DATE] date,
    CommunicationType varchar(10)
)
INSERT INTO #Data
    (ActivityID, Property, [DATE], CommunicationType)
VALUES
    (1046,  'Red Property',    '20191030', 'field'),
    (10467, 'Red Property',    '20191029', 'field'),
    (10591, 'Red Property',    '20191028', 'calls'),
    (10971, 'Blue Property',   '20191027', 'field'),
    (10971, 'Blue Property',   '20191026', 'field'),
    (10971, 'Blue Property',   '20191026', 'calls'),
    (10965, 'Green Property',  '20191024', 'calls'),
    (10765, 'Green Property',  '20191023', 'calls'),
    (10765, 'Green Property',  '20191019', 'field'),
    (10765, 'Green Property',  '20191015', 'field'),
    (10765, 'Green Property',  '20191012', 'field')
Run Code Online (Sandbox Code Playgroud)

陈述:

SELECT 
    *,
    CASE 
        WHEN CommunicationType = 'field' THEN DENSE_RANK() OVER (PARTITION BY Property, CommunicationType ORDER BY [DATE] ASC)
        ELSE NULL
    END AS Rank
FROM #Data
Run Code Online (Sandbox Code Playgroud)

结果:

ActivityID  Property    DATE        CommunicationType   Rank
10971   Blue Property   2019-10-26  calls               NULL
10971   Blue Property   2019-10-26  field               1
10971   Blue Property   2019-10-27  field               2
10765   Green Property  2019-10-23  calls               NULL
10965   Green Property  2019-10-24  calls               NULL
10765   Green Property  2019-10-12  field               1
10765   Green Property  2019-10-15  field               2
10765   Green Property  2019-10-19  field               3
10591   Red Property    2019-10-28  calls               NULL
10467   Red Property    2019-10-29  field               1
1046    Red Property    2019-10-30  field               2
Run Code Online (Sandbox Code Playgroud)