简体   繁体   中英

Count distinct value pairs in multiple columns in SQL

What query will count the number of rows, but distinct by three parameters?

Example:

Id      Name        Address 
==============================
1     MyName        MyAddress
2     MySecondName  Address2

Something like:

select count(distinct id,name,address) from mytable

To get a count of the number of unique combinations of id , name and address :

SELECT Count(*)
FROM   (
        SELECT DISTINCT
               id
             , name
             , address
        FROM   your_table
       ) As distinctified

获取所有不同的idnameaddress列并计算结果行。

SELECT COUNT(*) FROM mytable GROUP BY id, name, address

我刚刚想出的另一种(可能不是生产就绪或推荐的)方法是将值连接到一个字符串并特别地计算这个字符串:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

您还可以执行以下操作:

SELECT COUNT(DISTINCT id + name + address) FROM mytable

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM