[英]SQL - ORDER BY Works in Sub-query, But Fails in Full Query
I'm trying to set up a dynamic query to populate average payments over a dynamic period of months. 我正在尝试建立一个动态查询,以填充动态几个月内的平均付款。 I have a working query, but it provides the months out of order. 我有一个有效的查询,但是它提供了数月的故障。
I assign the months to a variable, @columns, and use that in the main query to determine the fields for a PIVOT command. 我将月份分配给变量@columns,然后在主查询中使用它来确定PIVOT命令的字段。 The following is how the variable is set up; 以下是变量的设置方式;
As can be seen, the months are out of order. 可以看出,几个月是乱序的。
But, if I run just the sub-query; 但是,如果我只运行子查询;
It orders fine. 命令很好。
What's going on? 这是怎么回事? Any thoughts? 有什么想法吗?
Thanx in advance! 提前感谢!
(hopefully, the images come out as I want) (希望这些图像能按我的意愿出来)
In your outer select you need to specify ORDER BY
to guarantee the order. 在外部选择中,您需要指定ORDER BY
以保证顺序。 Currently you are only ordering your derived table and not the final query. 当前,您仅订购派生表,而不订购最终查询。
SELECT @columns += ',' + QUOTENAME(Eff_Period)
FROM
(derived table) AS Raw_Data
ORDER BY Eff_Period
PRINT @columns
SELECT @columns == ',' + QUOTENAME (Eff_period)
FROM ( ... ) as Raw_Data
ORDER BY Eff_period
I think the subquery is unnecessary if all you need additionally is to concatenate the text ',' + + QUOTENAME(Eff_Period)
. 我认为,如果您仅需要连接文本',' + + QUOTENAME(Eff_Period)
则子查询是不必要的。 But you can just do this without a subquery. 但是,您无需子查询就可以执行此操作。 Also, the TOP 100 PERCENT
does not work as others have pointed out, it's not needed in any case. 另外, TOP 100 PERCENT
不能像其他人指出的那样工作,在任何情况下都不需要。
SELECT @column += ',' + QUOTENAME(Eff_Period)
FROM Members_Data AS Mbrs
INNER JOIN Claims_Data AS Clms
ON Mbrs.Eff_Period = REPLACE(CONVERT(nvarchar(7), Clms.Date_of_Service, 121), '-', '')
WHERE YEAR(Clms.Date_of_Service) = 2016
GROUP BY Mbrs.Eff_Period
ORDER BY Eff_Period
Also... I had to re-type the entire text from the screenshot. 另外...我必须重新输入屏幕快照中的整个文本。 Not a big deal to some people, but this is one reason we prefer the text versus screenshot. 对某些人来说并不重要,但这是我们偏爱文本而不是屏幕截图的原因之一。
Yes, the outside ORDER BY was the answer. 是的,外面的ORDER BY是答案。
I thought ORDER BY had to use field names and, as there was none, I had no clue how to put it in there. 我以为ORDER BY必须使用字段名,而且由于没有字段名,因此我不知道如何将其放在其中。 I tried using the ordinal, 1, unfortunately that only gave me the final value in the concatenated list. 我尝试使用序数1,但不幸的是,这仅给了我串联列表中的最终值。
But, it appears that it can take Eff_Period in the outside SELECT ; 但是,似乎可以在外部SELECT中使用Eff_Period了; perhaps because it's a unique name from the JOIN . 也许是因为它是JOIN中的唯一名称。
However, that answered the problem I was having. 但是,这回答了我遇到的问题。 A problem that arose from an answer that I thought fixed an overlying problem, but I have discovered does not. 我认为可以解决以上问题的答案引起了一个问题,但我没有发现。 I'm trying to figure that out at this time. 我正在设法解决这个问题。
Thanx to everyone who responded! 感谢所有做出回应的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.