简体   繁体   English

Sql 查询用于选择多列中的不同值

[英]Sql query for selecting the distinct values in multiple columns

I have a table say which has two columns zip code and customer code .我有一张表说它有两列zip code and customer code Suppose there are multiple customer code with same zipcode .假设有多个具有相同zipcodecustomer code I need to fetch the above two columns such that one column contains unique zipcode and the second column contains the number of unique customer codes for the corresponding zip code.我需要获取上述两列,以便一列包含唯一邮政编码,第二列包含相应 zip 代码的唯一客户代码的数量。

The problem here is there can be more than one unique customer for a single zip code(Kind of like a single customer might have gone to a shop in same zip code more than once but I need to treat them as one)这里的问题是单个 zip 代码可能有多个唯一客户(有点像单个客户可能不止一次去过同一个 zip 代码的商店,但我需要将它们视为一个)

How can I do it in SQLite .我该如何在SQLite中做到这一点。 I did the following SQL query and I get only single zip code我做了以下SQL query ,我只得到一个zip code

select distinct(C.pin_code),count(distinct(C.customer_code)) from customers as C inner join Sales as S on S.customer_code=C.customer_code

The output is output 是

在此处输入图像描述

I don't know how this comes about.If you need any more info please let me know in comments.我不知道这是怎么回事。如果您需要更多信息,请在评论中告诉我。

You are describing group by :您正在描述group by

select zip_code, count(distinct customer_code)
from t
group by zip_code;

I have no idea what your query has to do with the question.我不知道您的查询与该问题有什么关系。 The question is explicitly about a single table with two columns.这个问题明确地是关于一个有两列的表。

Note: You probably don't need count(distinct) -- unless there are multiple rows for a single customer in a single zip code.注意:您可能不需要count(distinct) - 除非单个 zip 代码中有多个行用于单个客户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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