我有一张这样的 table
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
我想添加一列,按 col1ID 和 col3ID 计算我在 col4String 组中有多少个不同的字符串。
类似
COUNT(DISTINCT (Col4String)) over (partition by col1ID, col3ID)
但它不起作用,我收到一个错误
Use of DISTINCT is not allowed with the OVER clause.
Msg 102, Level 15, State 1, Line 23.
我有更多列,例如 col2String、col5Data,但它们不应该受到影响,所以我不能在 SELECT
和 dense_rank()
的开头使用 distinct在我的情况下似乎也不起作用。
感谢您的帮助。
最佳答案
试试这个:
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
关于sql - 通过sql对分区计数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517860/