SQL中如何將表的查詢結果縱向顯示(個人思路總結)

下面看例子:
OOrders表結構是這樣的
OOrders
現在要查詢Customer的不同名字分別有多少個,並且要如下顯示:
result

1、於是我想到了用group by,那麼使用下面的語句:

select COUNT(Customer) as Customers from oorders GROUP by customer

會發現查出來的結果是這樣的:
result2
結果不對。

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

查詢出來的結果是這樣的:
result3
重複列好多,結果還是不對。

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

查詢結果:
result4
結果正確。

不知道大神的方法是怎麼樣的,希望多多指點

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章