我的SQL Server查询需要帮助

时间:2017-05-15 13:09:14

标签: sql sql-server

我无法运行查询来获取我想要的数据。

我写了这段代码

SELECT C.topic, C.lastupdate, C.[MONTHN], SUM(CAST(C.Number AS Int)) FROM
(SELECT B.topic, B.lastupdate, B.[MONTHN], COUNT(B.[MONTHN]) as Number FROM
(SELECT A.topic, A.lastupdate, DATENAME(month,lastupdate) as [MONTHN] FROM
(SELECT topic, lastupdate from DACHFAQ) AS A) as B) AS C 
GROUP BY C.topic, C.lastupdate, C.[MONTHN];

但是MS服务器正在告诉

  

列'B.topic'在选择列表中无效,因为它不是   包含在聚合函数或GROUP BY子句中。

我不知道如何纠正这个问题。

我需要以这样的顺序获取数据: 主题(不同),月份(不同),该月份的更新总和

我是SQL的新手,这就是我寻求帮助的原因,

感谢您在此提出的意见我提出了解决方案: 像ADyson写道我需要添加一个Groupby子句

SELECT C.topic, C.[MONTHN], SUM(Number) FROM
(SELECT B.topic, B.lastupdate, B.[MONTHN], COUNT(B.[MONTHN]) as Number FROM
(SELECT A.topic, A.lastupdate, DATENAME(month,lastupdate) as [MONTHN] FROM
(SELECT topic, lastupdate from DACHFAQ) AS A) as B
GROUP BY B.topic, B.lastupdate, B.[MONTHN]) as C 
GROUP BY C.topic, C.[MONTHN];

感谢您的支持!

1 个答案:

答案 0 :(得分:3)

它并不是很清楚你想要什么,但如果你想要的是主题,月份,更新总数,那么这可能是你想要的:

SELECT Topic, 
    DATENAME(month,lastupdate) as [MONTHN], 
    COUNT(*)
FROM DACHFAQ
GROUP BY Topic, DATENAME(month,lastupdate)

现在,您可能还需要考虑这一年。