SQL Select 联合后的最大日期
SQL Select Max Date after a Union
我想 select 三个联合行记录中的最高日期(基于我的 SQL 查询),但我遇到了这个错误:
Column 'tbl1.intDocID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SELECT TOP 1
a.YearX, intClientCode
FROM
(SELECT intDocID, MAX(dtY1) AS YearX, 1 AS position
FROM [tbl1] WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY2, 2 FROM [tbl1]
WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY3, 3 FROM [tbl1]
WHERE intDocID = '834') a
ORDER BY
a.YearX DESC
您需要在 select 语句中添加 GROUP BY 子句。 GROUP BY 语句需要聚合函数(COUNT、MAX、MIN、SUM、AVG)按一个或多个列对结果集进行分组
SELECT TOP 1
a.YearX, intClientCode
FROM
(SELECT intDocID, MAX(dtY1) AS YearX, 1 AS position FROM [tbl1]
WHERE intDocID = '834'
GROUP BY intDocID
UNION ALL
SELECT intDocID, dtY2, 2 FROM [tbl1]
WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY3, 3 FROM [tbl1]
WHERE intDocID = '834') a
ORDER BY a.YearX desc
我想 select 三个联合行记录中的最高日期(基于我的 SQL 查询),但我遇到了这个错误:
Column 'tbl1.intDocID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SELECT TOP 1
a.YearX, intClientCode
FROM
(SELECT intDocID, MAX(dtY1) AS YearX, 1 AS position
FROM [tbl1] WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY2, 2 FROM [tbl1]
WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY3, 3 FROM [tbl1]
WHERE intDocID = '834') a
ORDER BY
a.YearX DESC
您需要在 select 语句中添加 GROUP BY 子句。 GROUP BY 语句需要聚合函数(COUNT、MAX、MIN、SUM、AVG)按一个或多个列对结果集进行分组
SELECT TOP 1
a.YearX, intClientCode
FROM
(SELECT intDocID, MAX(dtY1) AS YearX, 1 AS position FROM [tbl1]
WHERE intDocID = '834'
GROUP BY intDocID
UNION ALL
SELECT intDocID, dtY2, 2 FROM [tbl1]
WHERE intDocID = '834'
UNION ALL
SELECT intDocID, dtY3, 3 FROM [tbl1]
WHERE intDocID = '834') a
ORDER BY a.YearX desc