首页 > 解决方案 > 需要使用自定义模式在另一个表中插入数据

问题描述

我有像这些列一样的表名“table1”:

id  code  price

1   1000  5.3
2   1001  4.3
3   1002  6.5
4   1003  7.5 

我需要将这些数据插入到表“table2”中,如下所示:

id  code  price   code1   price2

1   1000  5.3     1001    4.3
2   1002  6.5     1003    7.5 

问题:这可能吗?如果是这样,我该怎么做?

标签: sqlsql-server

解决方案


您可以使用以下方法将偶数和奇数代码放在单独的列中:

select row_number() over (order by min(code)) as id,
       max(case when code % 2 = 1 then code end) as id_1,
       max(case when code % 2 = 1 then price end) as price_1,
       max(case when code % 2 = 0 then code end) as id_2,
       max(case when code % 2 = 0 then price end) as price_2
from t
group by ceiling(code / 2.0)

推荐阅读