我会承认,小组总是给我带来问题,也许是因为我不明白它的正确使用,但希望一旦我看到它如何完成,我就会理解更多。
我的陈述:
SELECT DATENAME(month, A.[endTime]) as [month],
MONTH(A.[endTime]) as [monthValue],
(
SELECT count(employee) as attendees FROM Focus_Attendees WHERE meetingID = A.[id]
) as attendees,
(
SELECT count(id) as totalMeetings FROM Focus_Meetings WHERE id = A.[id]
) as totalMeetings
FROM Focus_Meetings as A
WHERE YEAR(endTime) = @year
GROUP BY DATENAME(month, A.[endTime]), MONTH(A.[endTime])
FOR XML PATH ('dataSet'), TYPE, ELEMENTS, ROOT ('root');
Column 'Focus_Meetings.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我不想按ID对数据进行分组,因为每个结果都有一条单独的记录。我的桌子包含会议,我试图获得每月的会议总数,然后是那次会议的与会者人数。
通过调整声明来实现这一目标的任何建议?
更新
我将其更改为此查询:
SELECT DATENAME(month, A.[endTime]) as [month],
MONTH(A.[endTime]) as [monthValue],
count(B.[employee]) as totalAttendees
FROM Focus_Meetings as A
JOIN focus_attendees as B
ON A.[id] = B.[meetingID]
WHERE YEAR(endTime) = @year
GROUP BY DATENAME(month, A.[endTime]), MONTH(A.[endTime])
FOR XML PATH ('dataSet'), TYPE, ELEMENTS, ROOT ('root');
这将返回我的XML:
`<root>
<dataSet>
<month>July</month>
<monthValue>7</monthValue>
<totalAttendees>1</totalAttendees>
</dataSet>
<dataSet>
<month>June</month>
<monthValue>6</monthValue>
<totalAttendees>13</totalAttendees>
</dataSet>
</root>`
这是正确的但我还需要那个月的会议总数count(A.[id])
,但这会给我错误
答案 0 :(得分:1)
现在您按日期分组,但尝试按ID选择计数。
第一个想法是将子选择包装在SUM中,以便一个月内所有会议的所有与会者将汇总在一起。
您的陈述:
SELECT count(id) as totalMeetings FROM Focus_Meetings WHERE id = A.[id]
) as totalMeetings
毫无意义。如果id是主键,那么您将加入自己并始终获得1.只需将该行替换为count(*)即可获得一个月内的总会议数。
答案 1 :(得分:1)
使用联接。
SELECT DATENAME(month, A.[endTime]) as [month],
MONTH(A.[endTime]) as [monthValue],
count(employee) ,
count(distinct A.[Id])
FROM Focus_Meetings as A
LEFT JOIN Focus_Attendees B ON B.meetingID = A.[id]
WHERE YEAR(A.endTime) = @year
GROUP BY DATENAME(month, A.[endTime]), MONTH(A.[endTime])
FOR XML PATH ('dataSet'), TYPE, ELEMENTS, ROOT ('root');
免责声明:我没有运行查询,因此可能需要进行一些小的调整。