简体   繁体   English

如何根据 sql 中不同列中的标识符按列中的值排序

[英]How to sort by values in a column based on identifiers in a different column in sql

This would be our input:这将是我们的输入:

NAME姓名 YEAR VALUES价值观
A一个 2001 2001年 10 10
A一个 2000 2000 5 5
A一个 TOTAL全部的 15 15
B 2010 2010 3 3
B 2011 2011 7 7
B TOTAL全部的 10 10

We have to sort this table by ascending values of 'TOTAL' and then by ascending values of YEAR within the same NAME.我们必须通过升序“TOTAL”的值,然后在同一NAME 中升序YEAR 的值来对该表进行排序。

This would be our output:这将是我们的 output:

NAME姓名 YEAR VALUES价值观
B 2010 2010 3 3
B 2011 2011 7 7
B TOTAL全部的 10 10
A一个 2000 2000 5 5
A一个 2001 2001年 10 10
A一个 TOTAL全部的 15 15

I think I'd sum all values partitioned by name in a CTE, sort by them, then name, then year (with a special case for total)我想我会将 CTE 中按名称分区的所有值相加,按它们排序,然后按名称排序,然后按年份(总计有特殊情况)

WITH cte AS (
    SELECT *, SUM(values) OVER(PARTITION BY name) as sumval
    FROM yourdata
)

SELECT name, year, values
FROM cte
ORDER BY sumval, name, CASE WHEN year = 'TOTAL' THEN '9999' ELSE year end

You could also join your data to itself on just the total lines, meaning every row of yourdata ends up with an associated totals row:您还可以仅在总计行上将数据连接到自身,这意味着您的数据的每一行都以关联的总计行结束:

SELECT yourdata.*
FROM
  yourdata
  INNER JOIN (SELECT name, values FROM yourdata WHERE year = 'TOTAL') t
  ON t.name = yourdata.name
ORDER BY
  t.values, yourdata.name, CASE WHEN year = 'TOTAL' THEN '9999' ELSE year end

eg例如

B   2010    3   TOTAL   10
B   2011    7   TOTAL   10
B   TOTAL   10  TOTAL   10
A   2000    5   TOTAL   15
A   2001    10  TOTAL   10
A   TOTAL   15  TOTAL   10

The final column is the total row for the name repeated over and over, so you can sort by the total, then by name to break ties, then by year (with 9999 to put the total after the numeric years)最后一列是名称反复重复的总行,因此您可以按总数排序,然后按名称以打破平局,然后按年份(9999 将总数放在数字年份之后)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM