简体   繁体   English

SQL:如何检查一列中的每个唯一值可以找到另一列的多少组合

[英]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第 1 列 Column 2第 2 栏
A一个 1 1
A一个 1 1
A一个 1 1
B 1 1
B 2 2
B 3 3
C C 2 2
C C 2 2
C C 3 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

dbfiddle here dbfiddle在这里

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.

相关问题 在标准SQL中,如何选择行,以便对于一列中的每个唯一值,另一列中的所有值都是指定值? - In standard SQL, how do I select rows such that for each unique value in one column, all of the values in another column are a specified value? SQL对另一列中的每个唯一值求和一个值 - SQL sum one value for each unique value from another column 如何将行中的数据映射到一行,以便每一列在SQL中都是唯一值 - How can I map data in rows into one row such that each column is a unique value in SQL 如何在 SQL 中查找表列的唯一组合? - How to find unique combinations for a table column in SQL? 如何创建SQL查询以获取另一列的每个GROUP'ed BY值的列的唯一值 - How to create SQL query to get unique values of column for each GROUP'ed BY value of another column 如何为列中找到的每个唯一值插入行 - How to insert row for each unique value found in column 基于另一列的所有唯一组合 - All unique combinations of a column based on another one 如何检查一列的值是否在另一行的另一列中 - How to check if value of one column is in another column of another row SQL-从一列返回所有唯一的值对,在另一列中返回每个值 - SQL - Return all unique pairs of values from one column, for each value in another column 如何使用SQL检查一列中的字符串值是否部分包含在另一列的字符串值中? - How to check if string value in one column is partially contained in string value of another column using SQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM