票证具有ID,TicketNbr和时间条目具有ID,Time_RecID。门票有与TicketNbr相关联的0,1或可能更多的时间条件。
我正在尝试生成如下列表:
Time Entries | Tickets
10 | #
9 | #
8 | #
7 | #
6 | #
5 | #
4 | #
3 | #
2 | #
1 | #
其中#是门票数量。
数据来自两个表:v_rpt_Service(TicketNbr)和v_rpt_Time(Time_RecID)。使用以下SQL发现我的所有相关数据:
SELECT
s.TicketNbr, t.Time_RecID
FROM
v_rpt_Service s
LEFT JOIN v_rpt_time t on s.TicketNbr = t.SR_Service_RecID
我正在努力的是聚合。理想情况下,我正在寻找的是:
SELECT
COUNT(T.Time_recID) as Time_Entries, COUNT(DISTINCT(s.TicketNbr)) as Tickets
FROM
v_rpt_Service s
LEFT JOIN v_rpt_time t on s.TicketNbr = t.SR_Service_RecID
GROUP BY
COUNT(t.Time_recID)
会导致此错误:
Msg 144,Level 15,State 1,Line 8 不能在GROUP BY子句列表的组表达式中使用聚合或子查询。
如何重构初始查询以提供类似上面列表的输出?
答案 0 :(得分:1)
SELECT q.TimeEntries,count(q.TicketNbr) As Tickets
FROM ( SELECT
s.TicketNbr, count(t.Time_RecID) As TimeEntries
FROM
v_rpt_Service s
LEFT JOIN v_rpt_time t on s.TicketNbr = t.Time_RecID
GROUP BY s.TicketNbr) As q
GROUP BY q.TimeEntries
ORDER BY q.TimeEntries DESC
您可能需要考虑当故障单没有时间条目时会发生什么(我认为LEFT JOIN
答案 1 :(得分:1)
您可以创建嵌套查询:
SELECT TicketNbr, count(Time_RecID)
FROM
(SELECT
s.TicketNbr, t.Time_RecID
FROM
v_rpt_Service s
LEFT JOIN v_rpt_time t on s.TicketNbr = t.Time_RecID) AS table
GROUP BY
Time_RecID