每月/每年报告的SQL查询

时间:2012-02-17 16:09:06

标签: sql database sql-server-2008 select

我有一个Sales表,其中包含

等字段
   upgrade[yes/no] 
   date upgraded[datetime] 
   user[username]

我想运行一个查询并每月和每年显示升级,例如我想生成一个类似2012年1月的报告[总升级30次,user1进行10次升级,用户2进行15次升级,类似 用户3进行了5次升级。同样,我也希望每年都能实现这一目标。

2 个答案:

答案 0 :(得分:1)

SELECT USERNAME,
CONVERT(CHAR(7), DATE_FIELD,120) AS MONTH,
SUM(CASE WHEN UPGRADE = 'YES' THEN 1 ELSE 0 END) UPGRADED
FROM TABLE
GROUP BY USERNAME, CONVERT(CHAR(7), DATE_FIELD,120)

答案 1 :(得分:1)

使用SSRS,您可以非常轻松地生成多个分组,并一目了然地显示所有这些信息。

在vanilla T-SQL查询中,您可以这样做:

SELECT
    YEAR(s.[date upgraded]),
    s.[user],
    COUNT(*) AS [total upgrades]
FROM [Sales] s
WHERE s.[upgrade] = 'yes'
GROUP BY s.[user], YEAR(s.[date upgraded]) WITH ROLLUP
ORDER BY YEAR(s.[date upgraded]), s.[user]

SELECT
    MONTH(s.[date upgraded]),
    s.[user],
    COUNT(*) AS [total upgrades]
FROM [Sales] s
WHERE s.[upgrade] = 'yes'
GROUP BY s.[user], MONTH(s.[date upgraded]) WITH ROLLUP
ORDER BY MONTH(s.[date upgraded]), s.[user]