添加导致 GROUP BY 错误的聚合列
Adding an aggregate column causing GROUP BY error
我正在向我的查询添加聚合列 min(finumber)
。添加此号码后,我希望能够在 ORDER BY
中使用它。当我删除 min(finumber)
时,查询工作正常。当我添加 min(finumber)
时,出现错误:
Column 'soitem.fsono' is invalid in the select list because it is not
contained in either an aggregate function or the GROUP BY clause.
我的问题是:如何添加 min(finumber)
并将其用于 ORDER BY
我的数据?
SELECT A.fsono,
MAX(A.Attention) AS Attention,
MAX(A.Address1) AS Address1,
MAX(A.Address2) AS Address2,
A.fcustno,
A.fcontact,
A.min_fin
FROM (SELECT soitem.fsono,
somast.fcustno,
somast.fcontact,
min(finumber)as min_fin,
CASE
WHEN (CONVERT(varchar(MAX), soship.fmstreet)) LIKE 'ATTN%' THEN LEFT(CONVERT(varchar(MAX), soship.fmstreet), CHARINDEX(CHAR(10), CONVERT(varchar(MAX), soship.fmstreet)))
ELSE NULL
END AS Attention,
CASE WHEN [id] = 2 THEN S.val ELSE NULL END AS Address1,
CASE WHEN [id] = 3 THEN S.val ELSE NULL END AS Address2
FROM soitem
INNER JOIN somast ON soitem.fsono = somast.fsono
LEFT OUTER JOIN soship ON somast.fsono = soship.fcsono
AND soship.fcenumber = ''
CROSS APPLY [dbo].[split3](soship.fmstreet, CHAR(13) + CHAR(10)) S
WHERE (somast.fstatus <> 'Cancelled')
AND (somast.fsocoord = 'IFP'
OR somast.fsocoord = '711')
AND somast.fsono >= '034023') A
GROUP BY A.fsono,
A.fcustno,
A.fcontact
Order by A.fsono, A.min_fin
;
错误在这里告诉你问题。
min(finumber)
在您的子查询中,而不是您的主查询中。您的子查询没有 GROUP BY
,因此出现错误。您需要使用 OVER
子句。这是伪 SQL,但是:
MIN(finumber) OVER (PARTITION BY {Partition Columns}) AS min_fin
我猜这些列应该是 soitem.fsono, somast.fcustno, somast.fcontact
。
我正在向我的查询添加聚合列 min(finumber)
。添加此号码后,我希望能够在 ORDER BY
中使用它。当我删除 min(finumber)
时,查询工作正常。当我添加 min(finumber)
时,出现错误:
Column 'soitem.fsono' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
我的问题是:如何添加 min(finumber)
并将其用于 ORDER BY
我的数据?
SELECT A.fsono,
MAX(A.Attention) AS Attention,
MAX(A.Address1) AS Address1,
MAX(A.Address2) AS Address2,
A.fcustno,
A.fcontact,
A.min_fin
FROM (SELECT soitem.fsono,
somast.fcustno,
somast.fcontact,
min(finumber)as min_fin,
CASE
WHEN (CONVERT(varchar(MAX), soship.fmstreet)) LIKE 'ATTN%' THEN LEFT(CONVERT(varchar(MAX), soship.fmstreet), CHARINDEX(CHAR(10), CONVERT(varchar(MAX), soship.fmstreet)))
ELSE NULL
END AS Attention,
CASE WHEN [id] = 2 THEN S.val ELSE NULL END AS Address1,
CASE WHEN [id] = 3 THEN S.val ELSE NULL END AS Address2
FROM soitem
INNER JOIN somast ON soitem.fsono = somast.fsono
LEFT OUTER JOIN soship ON somast.fsono = soship.fcsono
AND soship.fcenumber = ''
CROSS APPLY [dbo].[split3](soship.fmstreet, CHAR(13) + CHAR(10)) S
WHERE (somast.fstatus <> 'Cancelled')
AND (somast.fsocoord = 'IFP'
OR somast.fsocoord = '711')
AND somast.fsono >= '034023') A
GROUP BY A.fsono,
A.fcustno,
A.fcontact
Order by A.fsono, A.min_fin
;
错误在这里告诉你问题。
min(finumber)
在您的子查询中,而不是您的主查询中。您的子查询没有 GROUP BY
,因此出现错误。您需要使用 OVER
子句。这是伪 SQL,但是:
MIN(finumber) OVER (PARTITION BY {Partition Columns}) AS min_fin
我猜这些列应该是 soitem.fsono, somast.fcustno, somast.fcontact
。