總是發佈DDL和INSERT語句。這是我期望的。
create table companies (
id integer primary key,
name varchar(10)
);
create table contacts (
id integer primary key,
company_id integer references companies (id)
);
insert into companies values (1, 'First');
insert into companies values (2, 'Second');
insert into companies values (3, 'Third');
-- Companies 'First' and 'Third' both have 3 contacts.
insert into contacts values (100,1);
insert into contacts values (101,1);
insert into contacts values (102,1);
insert into contacts values (201,2);
insert into contacts values (301,3);
insert into contacts values (302,3);
insert into contacts values (303,3);
您的第一個查詢。
SELECT comp.Name , count(cc.Id) CCount
FROM Contacts cc JOIN Companies comp ON comp.Id = cc.Company_id
GROUP BY comp.Name
ORDER BY CCount desc, comp.Name desc
name ccount
--
Third 3
First 3
Second 1
ORDER BY CCount desc
將會把較大的數字在頂部。在每組相同的計數中,名稱將按降序排列。 「Second」在最後一行,因爲它的計數爲1.
您的第二個查詢。
SELECT comp.Name , count(cc.Id) CCount
FROM Contacts cc JOIN Companies comp ON comp.Id = cc.Company_id
GROUP BY comp.Name
ORDER BY comp.Name desc, CCount desc
name ccount
--
Third 3
Second 1
First 3
ORDER BY comp.Name desc
將按公司名稱降序排列。在每組相同的公司名稱中,ccounts將按降序排列。由於不能有任何相同公司名稱的組(爲什麼?),對ccount的排序沒有任何影響。
你能告訴我們一些實際的結果,而你反而期待什麼? – AakashM
順序通過很好。這個問題似乎很奇怪 –
[t-clausen.dk]它是你有權利的問題,問題是奇怪;) – GregJaw