这是我的查询,
SELECT TOP (3)
a.INCIDENT_ID, a.REFERENCE, SUM(b.COST) AS TOTAL_COST
FROM
FDDC_T_D_INCIDENT AS a
INNER JOIN
FDDC_T_D_INCIDENT_COST AS b ON a.INCIDENT_ID = b.FINCIDENT_ID
WHERE
(a.CREATED_DATE >= @date1) AND (a.CREATED_DATE <= @date2)
GROUP BY
a.INCIDENT_ID
ORDER BY
TOTAL_COST DESC
我收到错误
专栏&#39; FDDC_T_D_INCIDENT.REFERENCE&#39;在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
有人可以帮我解决这个问题吗?
提前致谢!
答案 0 :(得分:0)
试试这个:
SELECT TOP (3) a.INCIDENT_ID, a.REFERENCE, SUM(b.COST) AS TOTAL_COST
FROM FDDC_T_D_INCIDENT AS a INNER JOIN
FDDC_T_D_INCIDENT_COST AS b ON a.INCIDENT_ID =b.FINCIDENT_ID
WHERE (a.CREATED_DATE >= @date1) AND (a.CREATED_DATE <= @date2)
GROUP BY a.INCIDENT_ID, a.REFERENCE
ORDER BY TOTAL_COST DESC
您需要将“a.REFERENCE”添加到GROUP BY子句中。
编辑:
如果您只想要GROUP BY'a.INCIDENT_ID':
,请尝试此操作SELECT INCIDENT_ID, REFERENCE, TOTAL_COST
FROM(
SELECT TOP (3) a.INCIDENT_ID, a.REFERENCE, SUM(b.COST) AS TOTAL_COST
FROM FDDC_T_D_INCIDENT AS a INNER JOIN
FDDC_T_D_INCIDENT_COST AS b ON a.INCIDENT_ID =b.FINCIDENT_ID
WHERE (a.CREATED_DATE >= @date1) AND (a.CREATED_DATE <= @date2)
GROUP BY a.INCIDENT_ID, a.REFERENCE
ORDER BY TOTAL_COST DESC
) AS T
GROUP BY INCIDENT_ID
希望这有帮助。
答案 1 :(得分:0)
尝试此操作,按Incident_ID分组并返回引用(如果事件有多个引用,将返回具有相同总成本的多行)。
SELECT TOP (3)
a.INCIDENT_ID, a.REFERENCE, SUM(b.COST) over (partition by a.incident_ID) AS TOTAL_COST
FROM
FDDC_T_D_INCIDENT AS a
INNER JOIN
FDDC_T_D_INCIDENT_COST AS b ON a.INCIDENT_ID = b.FINCIDENT_ID
WHERE
(a.CREATED_DATE >= @date1) AND (a.CREATED_DATE <= @date2)
ORDER BY
TOTAL_COST DESC