我正在向查询添加汇总列min(finumber)
。添加此号码后,我希望能够在ORDER BY
中使用它。当我删除min(finumber)
时,查询工作正常。当我添加min(finumber)
时出现错误:
选择列表中的列'soitem.fsono'无效,因为它不是 包含在聚合函数或GROUP BY子句中。
我的问题是:如何添加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
;
答案 0 :(得分:0)
错误在这里告诉您问题。
git
在子查询中,而不是主查询中。您的子查询没有min(finumber)
,因此出现错误。您需要使用GROUP BY
子句。但是,这是伪SQL:
OVER
我想那些列应该是MIN(finumber) OVER (PARTITION BY {Partition Columns}) AS min_fin
。