如何在 SQL 中从上到下垂直翻转列值

发布于 2025-01-15 10:28:27 字数 306 浏览 5 评论 0原文

如何在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2025-01-22 10:28:27

使用标准 SQL 是不可能的(至少在 2003 年之前),因为当未使用 ORDER BY 显式排序时,结果集是“无序集”。

这意味着您获得结果的顺序应该是完全随机的,并且从对给定查询的调用到对同一查询的下一次调用可能会有所不同。不过,大多数时候,您只需按照插入数据库的方式获取它们,但这并不能保证。例如,当使用高级 RDBM 时,您可以根据您之前执行的最后一个 ORDER BY 对条目进行排序。

这也是您在查询表时得不到任何行号的原因。因为这没有意义。

但是,自 SQL 2003 以来,引入了 OLAP 函数,包括 ROW_NUMBER()。由于上面暴露的原因,必须使用 OVER 子句对其进行“窗口化”,这会破坏初始顺序。但是您仍然可以依靠子查询来获取所有它们,并加入永远不会变化的列:

WITH subquery(c1,c2) AS (SELECT C1,1 AS C2 FROM yourtable)
  SELECT c1
    FROM subquery
ORDER BY row_number() OVER (PARTITION BY c2) DESC

不要使用 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 an OVER 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:

WITH subquery(c1,c2) AS (SELECT C1,1 AS C2 FROM yourtable)
  SELECT c1
    FROM subquery
ORDER BY row_number() OVER (PARTITION BY c2) DESC

Don't use RANK() as this will return the same "ex-æquo" row number if two rows are identical.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文