如何在 SQL 中从上到下垂直翻转列值
如何在SQL中从上到下垂直翻转没有任何特定顺序(既不是asc也不是desc)的列值?
示例:名为“Country”的表有一个包含值的列 c1
| C1 |
---------
| JAPAN |
| NEPAL |
| INDIA |
---------
现在我想显示结果集,如下所示:
| C1 |
----------
| INDIA |
| NEPAL |
| JAPAN |
----------
如果有人可以建议吗?
How to vertically flip the column values from top to bottom in SQL which are not in any specific order(neither asc nor desc)?
Example: Table named 'Country' has a single column c1 with values
| C1 |
---------
| JAPAN |
| NEPAL |
| INDIA |
---------
Now I want to display the Result-set as below:
| C1 |
----------
| INDIA |
| NEPAL |
| JAPAN |
----------
If anyone can kindly suggest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用标准 SQL 是不可能的(至少在 2003 年之前),因为当未使用
ORDER BY
显式排序时,结果集是“无序集”。这意味着您获得结果的顺序应该是完全随机的,并且从对给定查询的调用到对同一查询的下一次调用可能会有所不同。不过,大多数时候,您只需按照插入数据库的方式获取它们,但这并不能保证。例如,当使用高级 RDBM 时,您可以根据您之前执行的最后一个
ORDER BY
对条目进行排序。这也是您在查询表时得不到任何行号的原因。因为这没有意义。
但是,自 SQL 2003 以来,引入了 OLAP 函数,包括
ROW_NUMBER()
。由于上面暴露的原因,必须使用OVER
子句对其进行“窗口化”,这会破坏初始顺序。但是您仍然可以依靠子查询来获取所有它们,并加入永远不会变化的列:不要使用
RANK()
因为这将返回相同的“ex-æquo”行号,如果两行相同。It's not possible using standard SQL (at least before 2003) because when not explicitly ordered using
ORDER BY
, a resultset is an "unordered set".This means that the order you'll get your results is supposed to be totally random and may vary from a call to a given query to the next call to this same query. Most of the time, though, you'll simply get them the way they have been inserted into the database, but this is not guaranteed. When using advanced RDBMs, you may for instance get your entries sorted according to the last
ORDER BY
you did before.That's also why you don't get any row number when querying a table. Because it just doesn't make sense.
However, since SQL 2003, OLAP functions have been introduced, including
ROW_NUMBER()
. For the reasons exposed above, it has to be "windowed" using anOVER
clause, which breaks initial order. But you still can lean on a subquery to fetch them all, joining aside a column that will never vary:Don't use
RANK()
as this will return the same "ex-æquo" row number if two rows are identical.