Postgres:将单行转换为多行(unpivot)

时间:2017-11-02 13:54:31

标签: sql database postgresql data-manipulation unpivot

我有一张桌子:

Table_Name: price_list
---------------------------------------------------
| id | price_type_a | price_type_b | price_type_c |
---------------------------------------------------
| 1  |    1234      |     5678     |     9012     |
| 2  |    3456      |     7890     |     1234     |
| 3  |    5678      |     9012     |     3456     |
---------------------------------------------------

我需要在Postgres中选择一个查询结果,如下所示:

---------------------------
| id | price_type | price |
---------------------------
| 1  |  type_a    | 1234  |
| 1  |  type_b    | 5678  |
| 1  |  type_c    | 9012  |
| 2  |  type_a    | 3456  |
| 2  |  type_b    | 7890  |
| 2  |  type_c    | 1234  |
...

任何有关类似示例链接的帮助都非常感谢。

2 个答案:

答案 0 :(得分:8)

SELECT LATERAL加入一个VALUES表达式的单SELECT p.id, v.* FROM price_list p , LATERAL ( VALUES ('type_a', p.price_type_a) , ('type_b', p.price_type_b) , ('type_c', p.price_type_c) ) v (price_type, price); 完成工作:

use std::io;

fn main() {
    let mut main_string = String::new();

    println!("Please enter the string : ");
    io::stdin()
        .read_line(&mut main_string)
        .expect("Failed to read the input value");

    main_string = main_string.trim().to_string();
    println!("The trimmed string is : {}", main_string);

    let repeating_character = recurring_string_parser(main_string);

    println!(
        "The character which is first repeating is {}",
        repeating_character
    );
}

fn recurring_string_parser(main_string: String) -> char {
    let mut char_array = Vec::new();
    for each_char in main_string.chars() {
        let mut some_val = char_array.iter().find(|&&c| c == each_char);

        match some_val {
            Some(ch) => return each_char,
            _ => println!("do nothing"),
        }
        char_array.push(each_char);
        println!(" The charcater is {:?}", some_val);
    }

    return 'a';
}

相关:

答案 1 :(得分:0)

尝试像:

select id, 'type_a',type_a  from price_list
union all
select id, 'type_b',type_b  from price_list
union all
select id, 'type_c',type_c  from price_list
;

<强>更新 正如a_horse_with_no_name建议的那样,union是选择DISTINCT值的方法,因为这里优先UNION ALL - 以防万一(我不知道id是否是唯一的)

当然,如果是英国 - 没有区别