sql - Count Distinct over partition by sql
问题描述
I have a table like
col1ID col2String Col3ID Col4String Col5Data
1 xxx 20 abc 14-09-2018
1 xxx 20 xyz 14-09-2018
2 xxx 30 abc 14-09-2018
2 xxx 30 abc 14-09-2018
I would like to add column which count how many different strings I have in col4String group by col1ID and col3ID.
So something like
COUNT(DISTINCT (Col4String)) over (partition by col1ID, col3ID)
but it doesn't work, I receive an error
Use of DISTINCT is not allowed with the OVER clause.
Msg 102, Level 15, State 1, Line 23.
I have more columns like col2String, col5Data but they shouldn´t be affected, so I can't use distinct at the beginning of SELECT
, and dense_rank()
also doen´t seems to work in my case.
Thank You for help.
解决方案
尝试这个:
DECLARE @DataSource TABLE
(
[col1ID] INT
,[col2String] VARCHAR(12)
,[Col3ID] INT
,[Col4String] VARCHAR(12)
,[Col5Data] DATE
);
INSERT INTO @DataSource
VALUES (1, 'xxx', 20, 'abc', '2018-09-14')
,(1, 'xxx', 20, 'xyz', '2018-09-14')
,(2, 'xxx', 30, 'abc', '2018-09-14')
,(2, 'xxx', 30, 'abc', '2018-09-14');
SELECT *
,dense_rank() over (partition by col1ID, col3ID order by [Col4String]) + dense_rank() over (partition by col1ID, col3ID order by [Col4String] desc) - 1
FROM @DataSource
推荐阅读
- reactjs - 如果在我的 MERN 应用程序中删除另一张照片后单击一张照片,我会收到“this.props.comments.map is not a function”或其他错误
- android - Android Studio - 两个 Windows 的问题
- django - Docker:我如何使用从前端访问另一个容器中的服务?
- python - sqlalchemy.exc.NoReferencedTableError:外键找不到表
- html - react-bootstrap-sweetalert 警报没有出现在屏幕中央
- typescript - 打字稿:根据枚举值制作类型
- apache-spark-mllib - 如何使用坐标获取火花millib矩阵的元素
- c++ - std::string 的 front() 和 [0] 有区别吗?
- python - BeautifulSoup 中的网页抓取返回一个空列表
- file - 如何在 Flutter 的本地目录中监听文件的事件?