SQL查询,每月计算用户数(日期时间)

时间:2016-02-11 19:45:20

标签: sql sql-server datetime count

我有一个SQL表,我想将其更改为以下格式:

enter image description here

我已经拥有该表,但我无法将其计入另一个表中的用户并将其插入到列中。

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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))