我希望能够识别不同的值,包括表中每列的值计数。
我查看了 - Get distinct records with counts
它告诉我如何为单个列执行此操作并且效果很好。但是,我有一个包含超过600列的表格,每列编码都非常耗费时间。
有没有办法对我的sql进行编码,我可以在表中为所有列获得相同的结果,而无需单独输入每一列?
所以要使用链接中的示例:
personid, msg
-------------
1, 'msg1'
2, 'msg2'
2, 'msg3'
3, 'msg4'
1, 'msg2'
我的结果将是:
personid, count | msg, count
-----------------------------
1, 2 | msg1, 1
2, 2 | msg2, 2
3, 1 | msg3, 1
_, _ | msg4, 1
这可能吗?我尝试过使用区别和通配符(*)但没有运气。
道歉,如果这不够详细,这是我的第一篇文章,我不是SQL专家,谷歌搜索没有找到答案。感谢。
答案 0 :(得分:0)
我不确定这是否方便,但你可以这样做:
CREATE TABLE #temp (
personid int,
message nvarchar(max)
);
GO
INSERT INTO #temp
SELECT 1, 'msg1' UNION ALL
SELECT 2, 'msg2' UNION ALL
SELECT 2, 'msg3' UNION ALL
SELECT 3, 'msg4' UNION ALL
SELECT 1, 'msg2';
GO
SELECT
isnull(t1.rn, t2.rn) as rn,
t1.personid as personid, t1.cnt as personid_cnt,
t2.message as message, t2.cnt as message_cnt
FROM
(SELECT personid, count(*) as cnt,
ROW_NUMBER() over (order by personid) as rn
FROM #temp GROUP BY personid) t1
FULL JOIN
(SELECT message, count(*) as cnt,
ROW_NUMBER() over (order by message) as rn
FROM #temp GROUP BY message) t2
ON t1.rn = t2.rn
ORDER BY rn
DROP table #temp;
结果:
rn personid personid_cnt message message_cnt
1 1 2 msg1 1
2 2 2 msg2 2
3 3 1 msg3 1
4 NULL NULL msg4 1