SQL排序列A&更新B列

时间:2015-06-18 23:28:15

标签: mysql sql sorting

我的表格数据类似于:

library(plyr)
library(tidyr)
library(dplyr)
library(ggplot2)
library(scales)

set.seed(12345)

my_labels <- function(variable, value){
  names_li <- list("percentage", "cost in pounds")
  return(names_li[value])
}


df <- data.frame(
  rate = runif(10, 0, 1),
  cost = rnorm(10, 100, 40),
  years = seq(from = 2001, to = 2010)
)

df %>%
  gather(type_of_var,
         value,
         rate:cost) ->
  df2


df2 %>%
  ggplot(aes(x = years,
             y = value,
             ymin = 0,
             ymax = .1)) +
  facet_grid(type_of_var ~ .,
             scales = 'free_y',
             labeller = my_labels) +
  labs(x = "Year",
       y = "") +

  geom_point(subset = . (type_of_var == "rate")) +
  geom_line(subset = . (type_of_var == "rate"),
            colour = "grey") +
  ## the following two lines don't work
  # scale_y_continuous(subset = . (type_of_var == "rate"),
  #                   labels = percent) +

  geom_bar(subset = . (type_of_var == "cost"),
           stat = "identity") +

  theme_bw() +
  theme(strip.text.y = element_text(size = 15,
                                    colour = "black"),
        plot.title = element_text(lineheight = 0.8,
                                  face = "bold")) +
  scale_x_continuous(breaks = seq(2001, 2010, 1)) +
  labs(title = "free_y y axis labels")

我想在列DESCRIPT降序alpha(A - Z)上对表进行排序,然后更新列PRINTORDER,以便在完成时,PRINTORDER = 1的记录是最高的alpha(A)和记录的PRINTORDER的最高值将是alpha(Z)中的最低值。

这可以不使用临时列吗?如果不是,那不是一个交易破坏者,只是一种偏好。

期望的结果:

根据排序结果更新PrintOrder值

Inven    DESCRIPT     PrintOrder
---------------------------------
1        D             9
2        B             0
3        A             5
4        Z             0
5        X             1
.        .             .
.        .             .
.        .             .

3 个答案:

答案 0 :(得分:0)

这应该这样做:

Update T
set PRINTORDER = ASCII(UPPER(DESCRIPT)) - 64

而系统中A的ASCII为65。 :)

编辑:

正如你所说,可能会有更多内容,所以我们需要通过假设你有一个PK列名为Id来改变它:

UPDATE T
set PRINTORDER = T2.Order
FROM T
     INNER JOIN (SELECT IDENTITY(int, 1,1) AS Order,Id FROM T Order By DESCRIPT ASC) T2 ON T.Id=T2.Id

但是通过这种方式,即使两个记录具有相同的DESCRIPT最终会有不同的打印顺序,如果你想让它们保持不变,它可能会有点复杂。

编辑: 抱歉刚刚意识到你正在使用MySql,IDENTITY(int,1,1)来自SQL Server,基本上它会生成一个行号,你可能需要一些不同的东西:http://blog.sqlauthority.com/2014/03/08/mysql-generating-row-number-for-each-row-using-variable/

答案 1 :(得分:0)

我不清楚您是否要修改表或仅创建结果集。以下是使用标准SQL的后者的解决方案:

select Inven, Descript, row_number() over (order by Descript) as PrintOrder
from table t
order by Descript;

编辑:

在MySQL中,select看起来像是:

select t.*
from (select Inven, Descript, (@rn := @rn + 1) as PrintOrder
      from table t cross join (select @rn := 0) params
      order by Descript
     ) t
order by Inven;

update稍微复杂一些,因为您无法对进行排序以初始化变量:

update t
    set PrintOrder = (@rn := coalesce(@rn + 1, 1))
    order by Descript;

答案 2 :(得分:0)

到达我的办公室并与我的同事聊天后,提出的问题完全不准确。因此,我将关闭此主题,并打开一个新的主题,更准确地描述该问题。

谢谢Gordon&amp;西蒙对你的回答非常感谢。