count用法 - sql join group by




如何在同一個select語句中使用count和group (7)

你可以在COUNT裡面使用DISTINCT,就像milkovsky說的那樣

在我的情況下:

select COUNT(distinct user_id) from answers_votes where answer_id in (694,695);

這將拉回被認為與一次計數相同的user_id的回答票數

我有一個sql select查詢有一個group by。 我想計算群組後的所有記錄。 有沒有辦法直接從SQL? 例如,與用戶建立一個表格,我想選擇不同的城鎮和用戶總數

select town, count(*) from user
group by town

我想要在所有城鎮中都有一個專欄,而在所有行中都要有一個用戶數量的專欄。

總共有3個城鎮和58個用戶的結果的一個例子是:

Town         Count
Copenhagen   58
NewYork      58
Athens       58

借助Oracle,您可以使用分析功能:

select town, count(town), sum(count(town)) over () total_count from user
group by town

您的其他選項是使用子查詢:

select town, count(town), (select count(town) from user) as total_count from user
group by town

如果你想使用Select Count With Count選項,試試這個...

 select a.*, (Select count(b.name) from table_name as b where Condition) as totCount from table_name  as a where where Condition

如果你想按數量排序(聽起來很簡單,但我無法找到一堆答案),你可以這樣做:

        SELECT town, count(town) as total FROM user
        GROUP BY town ORDER BY total DESC


我知道這是一個舊的帖子,在SQL Server中:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

這將做你想做的事(城鎮名單,每個城市的用戶數量):

select town, count(town) 
from user
group by town

使用GROUP BY時,您可以使用大多數聚合函數

更新 (改變問題和評論之後)

您可以為用戶數量聲明一個變量,並將其設置為用戶數量,然後使用該數量進行選擇。

DECLARE @numOfUsers INT
SET @numOfUsers = SELECT COUNT(*) FROM user

SELECT DISTINCT town, @numOfUsers
FROM user






group-by