开发者

SQL query to count number of different values

开发者 https://www.devze.com 2023-02-16 08:44 出处:网络
x y A P A P B P B Q Hi, I need a query to return for all unique values of x, how开发者_JAVA百科 many different y\'s. So for the above data it would return:
x y

A P
A P
B P
B Q

Hi, I need a query to return for all unique values of x, how开发者_JAVA百科 many different y's. So for the above data it would return:

x count
A 1
B 2

Thanks


Use GROUP BY and COUNT(DISTINCT ...):

SELECT x, COUNT(DISTINCT y) AS cnt_y
FROM yourtable
GROUP BY x

Result:

x    cnt_y
A    1
B    2

Test data:

CREATE TABLE yourtable (x VARCHAR(100) NOT NULL, y VARCHAR(100) NOT NULL);
INSERT INTO yourtable (x, y) VALUES
('A', 'P'),
('A', 'P'),
('B', 'P'),
('B', 'Q');


This is the simple case for a GROUP BY statement.

Here's some code:

SELECT x, COUNT(DISTINCT y) AS y
FROM table
GROUP BY x;
0

精彩评论

暂无评论...
验证码 换一张
取 消