下面看例子:
OOrders表結構是這樣的
現在要查詢Customer的不同名字分別有多少個,並且要如下顯示:
1、於是我想到了用group by,那麼使用下面的語句:
select COUNT(Customer) as Customers from oorders GROUP by customer
會發現查出來的結果是這樣的:
結果不對。
2、既然是需要顯示3列,說明我需要3個結果,於是我改成下面的語句:
select (select COUNT(customer) from oorders where customer='Adams') as Adams,
(select COUNT(Customer) from oorders where customer='Carter') as Carter,
(select COUNT(Customer) from oorders where customer='Bush') as Bush
from oorders
查詢出來的結果是這樣的:
重複列好多,結果還是不對。
3、有很多重複列,於是我想到了使用distinct消除重複列,最後語句改成這樣:
select distinct (select COUNT(customer) from oorders where customer='Adams') as Adams,
(select COUNT(Customer) from oorders where customer='Carter') as Carter,
(select COUNT(Customer) from oorders where customer='Bush') as Bush
from oorders
查詢結果:
結果正確。
不知道大神的方法是怎麼樣的,希望多多指點