gos*_*amp 4 sql t-sql sql-server count distinct
我有一张像这样的桌子
\n\ncol1ID col2String Col3ID Col4String Col5Data\n 1 xxx 20 abc 14-09-2018\n 1 xxx 20 xyz 14-09-2018\n 2 xxx 30 abc 14-09-2018\n 2 xxx 30 abc 14-09-2018 \nRun Code Online (Sandbox Code Playgroud)\n\n我想添加列来计算 col4String 组中按 col1ID 和 col3ID 有多少个不同的字符串。
\n\n所以像
\n\nCOUNT(DISTINCT (Col4String)) over (partition by col1ID, col3ID)\nRun Code Online (Sandbox Code Playgroud)\n\n但它不起作用,我收到一个错误
\n\n\n\n\nOVER 子句中不允许使用 DISTINCT。
\n
\n 消息 102,级别 15,状态 1,第 23 行。
我有更多列,如 col2String、col5Data 但它们应该 \xc2\xb4t 受到影响,所以我不能在 的开头使用 unique SELECT,并且dense_rank()doen\xc2\xb4t 似乎也适用于我的情况。
谢谢你的帮助。
\n尝试这个:
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
Run Code Online (Sandbox Code Playgroud)