2016-02-11 88 views
-1

我有我想更改爲以下格式的SQL表:SQL查詢,每月用戶數(日期時間)

enter image description here

我已經有一個表,但我不能使其從另一個表中統計用戶並將其插入到列中。

+0

當你說你「無法」,你是什麼意思?你嘗試了什麼,它是如何失敗的? – Blorgbeard

+1

你在用什麼DBMS? SQL Server? MySQL的?甲骨文?還有別的嗎? – Siyual

+1

我認爲你應該(看)(編輯)在這裏:http://stackoverflow.com/questions/2722408/how-to-use-count-and-group-by-at-the-same-select-statement –

回答

0

我建議你,而不是表使用視圖這樣的:

CREATE VIEW vw_CountUsersPerMonth 
AS 

SELECT YEAR(SignUpTime) as [Year], 
     DATENAME(month,SignUpTime) AS [MonthName], 
     COUNT(UserID) AS [CountUsers] 
FROM Tbl_Users 
GROUP BY YEAR(SignUpTime), DATENAME(month,SignUpTime)) 
0

這應該做到這一點,如果你正在使用tSQL,但不同年份的相同月份呢?

;WITH CTE AS (
SELECT DATENAME(month,SignUpTime) AS [MonthName], 
     COUNT(UserID) AS [CountUsers] 
FROM Tbl_Users 
GROUP BY DATENAME(month,SignUpTime)) 

UPDATE A 
SET A.[CountUsers]=B.[CountUsers] 
FROM Tbl_CountUsersPerMonth AS A LEFT OUTER JOIN 
    CTE AS B ON A.[MonthName]=B.[MonthName] 
+0

我的數據庫是SQL Server。 – maorw

+0

@maorw那麼這應該適合你 –