sql - 向密集秩函数添加条件子句(Where)
问题描述
我想创建一个 Rank 函数来计算一个人访问财产的次数,BY DATE
但条件是不包括访问类别。'Calls'
DENSE_RANK() over(partition by activitytable.[Property]
ORDER BY activitytable.[Date] as Job rank
这样做会对我不想要的整个通讯表进行排名。
桌子
---- ActivityID ----------Property --------DATE ------CommunicationType ----------------Rank
1046 Red Property 30/10/2019 Field 2
10467 Red Property 29/10/2019 Field 1
10591 Red Property 28/10/2019 Calls
10971 Blue Property 27/10/2019 Field 2
10971 Blue Property 26/10/2019 Field 1
10971 Blue Property 26/10/2019 calls
10965 Green Property 24/10/2019 calls
10765 Green Property 23/10/2019 calls
10765 Green Property 19/10/2019 field 3
10765 Green Property 15/10/2019 field 2
10765 Green Property 12/10/2019 field 1
理想情况下,我希望表格看起来像上面一样,以忽略通信类型列的调用元素并仅计算字段类别。我怎么能这样做?
解决方案
You need to partition by Property
and CommunicationType
:
Table:
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')
Statement:
SELECT
*,
CASE
WHEN CommunicationType = 'field' THEN DENSE_RANK() OVER (PARTITION BY Property, CommunicationType ORDER BY [DATE] ASC)
ELSE NULL
END AS Rank
FROM #Data
Result:
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
推荐阅读
- javascript - 如何从创建方法以外的其他方法访问 Leaflet Map Markers 的 markerOptions?
- python - 循环遍历元组列表并删除它们
- python - 如何通过 Git Bash 和 Python 运行工作目录中的文件
- python - 如何使用 python 从网站中提取数据以获取数据表?
- javascript - Javascript Date.UTC() 返回前一天
- python - 读取行直到某个字符串并将其删除
- sql - 使用 CTE 向树数据添加排序覆盖
- angular - 基于使用 iif 运算符的条件使用 RxJS 进行嵌套 API 调用,导致超出最大调用堆栈大小
- sql - 如何解析具有多个下划线和破折号的字符串
- scala - Scala 中的深度存根