在为我的数据库编写SQL查询时需要帮助

时间:2019-07-16 02:19:00

标签: sql

尝试在SQL中将上表转换为下表格式:

enter image description here

我是SQL新手

1 个答案:

答案 0 :(得分:-1)

您可以执行以下操作:

select productnumber, 'price1' as prices, price1 as value
  from t where price1 <> 0 union
select productnumber, 'price2', price2 from t where price2 <> 0 union
select productnumber, 'price3', price3 from t where price3 <> 0 union
select productnumber, 'price4', price4 from t where price4 <> 0

结果:

productnumber  prices  value       
-------------  ------  -----
45678          price1     12           
45678          price2     43           
12345          price3     65           
45678          price1     32           
45678          price3      2            
12345          price2     43           
12345          price3    123          
45678          price3      5            
45678          price4      1            
45678          price2     12           
45678          price3      1            

为了记录,我曾经在PostgreSQL中测试的数据脚本是:

create table t (
  productnumber int,
  brand varchar(10),
  price1 int,
  price2 int,
  price3 int,
  price4 int,
  total int
);

insert into t (productnumber, brand, price1, price2, price3, price4, total) 
  values (12345, 'ami', 0, 0, 123, 0, 123),
         (12345, 'ami', 0, 43, 65, 0, 108),
         (45678, 'wax', 12, 43, 1, 0, 56),
         (45678, 'wax', 0, 0, 5, 0, 5),
         (45678, 'wax', 32, 12, 2, 1, 47);