[英]SQL: How to check for each unique value in one column how many combinations of another column can be found
Working in SSMS.在 SSMS 工作。 Based on a value in one column I want to count the number of different occurrences in another column.
根据一列中的值,我想计算另一列中不同出现的次数。 How would I go about to do that?
我将如何 go 这样做?
Basically for each unique value in Column 1, how many combinations of Column 2 can be found?基本上对于第 1 列中的每个唯一值,可以找到第 2 列的多少种组合?
So if table looks like this:因此,如果表如下所示:
Column 1![]() |
Column 2![]() |
---|---|
A![]() |
1 ![]() |
A![]() |
1 ![]() |
A![]() |
1 ![]() |
B![]() |
1 ![]() |
B![]() |
2 ![]() |
B![]() |
3 ![]() |
C ![]() |
2 ![]() |
C ![]() |
2 ![]() |
C ![]() |
3 ![]() |
Desired output would then be:所需的 output 将是:
A = 1 A = 1
B = 3 B = 3
C = 2 C = 2
Use COUNT(DISTINCT)
for this case with GROUP BY
:在这种情况下使用
COUNT(DISTINCT)
和GROUP BY
:
SELECT Col1, COUNT(DISTINCT Col2)
FROM YourTable
GROUP BY Col1
WITH CTE(Column1,Column2) AS
(
SELECT 'A', 1 UNION ALL
SELECT 'A' , 1 UNION ALL
SELECT 'A' , 1 UNION ALL
SELECT 'B' , 1 UNION ALL
SELECT 'B' , 2 UNION ALL
SELECT 'B' , 3 UNION ALL
SELECT 'C' , 2 UNION ALL
SELECT 'C' , 2 UNION ALL
SELECT 'C' , 3
)
SELECT C.COLUMN1,COUNT(DISTINCT C.COLUMN2)CNTT
FROM CTE AS C
GROUP BY C.Column1
CTE is an example you provided. CTE 是您提供的示例。 Please replace reference to it with reference to your table
请用您的表格替换对它的引用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.