我在公共表表达式(CTE)中使用递归来连接多个行。递归工作正常。但是在CTE之后的SELECT
语句中,我想只返回带有连接字符串的行。但我使用MAX(stringValue)它返回最短的字符串。当我使用MIN(stringValue)时,它返回正确的(最长的)字符串。那是为什么?
返回所有行时,这是CTE中的数据:
Row TableName Script
1 Activity This is a string that I created.
1 Table2 This is another string.
2 Table2 This is another string. This is another string.
1 Table3 Test string.
2 Table3 Test string. Test string 2.
3 Table3 Test string. Test string 2. Test string 3.
当我使用此查询仅返回具有MAX(行)的行时:
SELECT MAX(Row) AS RowNumber, MAX(TableName) AS Tbl, MAX(Script)
FROM CTE
GROUP BY TableName
我的结果是:
Row TableName Script
1 Activity This is a string that I created.
2 Table2 This is another string.
3 Table3 Test string.
返回正确的行但不是正确的脚本。 当我使用此查询时:
SELECT MAX(Row) AS RowNumber, MAX(Table) AS Tbl, MIN(Script)
FROM CTE
GROUP BY TableName
我得到了正确的数据,即。最长的字符串。 为什么是这样?
我在另一个查询中使用了这个,并返回了正确的字符串,即最长的字符串。
我担心这些结果会无法预测且不一致。
更新 我想返回这些行:
Row TableName Script
1 Activity This is a string that I created.
2 Table2 This is another string. This is another string.
3 Table3 Test string. Test string 2. Test string 3.
答案 0 :(得分:1)
您的max()
应该返回您想要的行。但是,您也可以使用以下方式获取最新版本:
select t.*
from (select cte.*, row_number() over (partition by table order by row desc) as seqnum
from cte
) t
where seqnum = 1;
这将返回具有最大row
的行。您还可以使用order by len(script) desc
获取最长的字符串。
我注意到您的代码不起作用同时使用table
和tablename
。我不确定这是否能解释意外的结果。