具有分组依据和行数的SQL

时间:2014-01-28 13:43:11

标签: sql

我有一张桌子:

ID | domain       | address
=======================================
 1 | example.com  | example.com/siteA
 2 | example.com  | example.com/siteB
 3 | example.com  | sub.example.com
 4 | example.com  | sub.example.com/dir
 5 | foobar.com   | foobar.com/site123
 6 | foobar.com   | foobar.com/site
 ...

现在我想知道一个域有多少“地址”

ID | domain       | count
==========================
 1 | example.com  | 4
 5 | foobar.com   | 4

我的陈述目前是

SELECT * FROM table GROUP BY domain

我知道这只是一张桌子,或者我应该把它分成两张?

3 个答案:

答案 0 :(得分:1)

SELECT domain, COUNT(domain) as Count FROM table GROUP BY domain

更新:获取ID

SELECT MIN(ID) ID, domain, COUNT(domain) as Count FROM table GROUP BY domain

OR,另一种方式:

SELECT 
 (SELECT MIN (ID) FROM table WHERE DOMAIN = A.DOMAN) AS ID
domain, 
COUNT(domain) as Count 
FROM table A GROUP BY domain

答案 1 :(得分:1)

<强> Read Group by

select min(ID) as ID,domain,count(1) as Count
from table 
group by domain

答案 2 :(得分:1)

您正在寻找此输出:

ID | domain       | count
==========================
 1 | example.com  | 4
 5 | foobar.com   | 4

这是查询(假设每个域的每个地址都是唯一的):

SELECT MAX(ID), domain, COUNT(*) as count FROM table GROUP BY domain