转置一个 select sql
transposed with one select sql
是否可以将第一个 table 与一个 select sql 互换以获得第二个 table,如图所示?
我已经在下面尝试过,但它远非完美。
'SELECT table1.licence_no, table1.plateno, table1.desc,
MAX(CASE WHEN axle_no = 1 THEN axle_dist ELSE NULL END) AS axle_dist_1,
MAX(CASE WHEN axle_no = 2 THEN axle_dist ELSE NULL END) AS axle_dist_2,
MAX(CASE WHEN axle_no = 3 THEN axle_dist ELSE NULL END) AS axle_dist_3,
MAX(CASE WHEN axle_no = 4 THEN axle_dist ELSE NULL END) AS axle_dist_4,
MAX(CASE WHEN axle_no = 5 THEN axle_dist ELSE NULL END) AS axle_dist_5,
from table1
group table1.licence_no, table1.plateno, table1.desc;'
您可以在子查询中使用 dense_rank()
来枚举 plateno
(或 plateno
/desc
组合),然后对这些列使用条件聚合:
SELECT t1.licence_no,
MAX(CASE WHEN seqnum = 1 THEN t1.plateno END) as plateno_1,
MAX(CASE WHEN seqnum = 1 THEN t1.desc END) as desc_1,
MAX(CASE WHEN seqnum = 2 THEN t1.plateno END) as plateno_2,
MAX(CASE WHEN seqnum = 2 THEN t1.desc END) as desc_2,
MAX(CASE WHEN axle_no = 1 THEN axle_dist ELSE NULL END) AS axle_dist_1,
MAX(CASE WHEN axle_no = 2 THEN axle_dist ELSE NULL END) AS axle_dist_2,
MAX(CASE WHEN axle_no = 3 THEN axle_dist ELSE NULL END) AS axle_dist_3,
MAX(CASE WHEN axle_no = 4 THEN axle_dist ELSE NULL END) AS axle_dist_4,
MAX(CASE WHEN axle_no = 5 THEN axle_dist ELSE NULL END) AS axle_dist_5
from (select1 t1.*,
dense_rank() over (partition by license_no order by plateno) as seqnum
from table1 t1
) t1
group t1.licence_no;
是否可以将第一个 table 与一个 select sql 互换以获得第二个 table,如图所示? 我已经在下面尝试过,但它远非完美。
'SELECT table1.licence_no, table1.plateno, table1.desc,
MAX(CASE WHEN axle_no = 1 THEN axle_dist ELSE NULL END) AS axle_dist_1,
MAX(CASE WHEN axle_no = 2 THEN axle_dist ELSE NULL END) AS axle_dist_2,
MAX(CASE WHEN axle_no = 3 THEN axle_dist ELSE NULL END) AS axle_dist_3,
MAX(CASE WHEN axle_no = 4 THEN axle_dist ELSE NULL END) AS axle_dist_4,
MAX(CASE WHEN axle_no = 5 THEN axle_dist ELSE NULL END) AS axle_dist_5,
from table1
group table1.licence_no, table1.plateno, table1.desc;'
您可以在子查询中使用 dense_rank()
来枚举 plateno
(或 plateno
/desc
组合),然后对这些列使用条件聚合:
SELECT t1.licence_no,
MAX(CASE WHEN seqnum = 1 THEN t1.plateno END) as plateno_1,
MAX(CASE WHEN seqnum = 1 THEN t1.desc END) as desc_1,
MAX(CASE WHEN seqnum = 2 THEN t1.plateno END) as plateno_2,
MAX(CASE WHEN seqnum = 2 THEN t1.desc END) as desc_2,
MAX(CASE WHEN axle_no = 1 THEN axle_dist ELSE NULL END) AS axle_dist_1,
MAX(CASE WHEN axle_no = 2 THEN axle_dist ELSE NULL END) AS axle_dist_2,
MAX(CASE WHEN axle_no = 3 THEN axle_dist ELSE NULL END) AS axle_dist_3,
MAX(CASE WHEN axle_no = 4 THEN axle_dist ELSE NULL END) AS axle_dist_4,
MAX(CASE WHEN axle_no = 5 THEN axle_dist ELSE NULL END) AS axle_dist_5
from (select1 t1.*,
dense_rank() over (partition by license_no order by plateno) as seqnum
from table1 t1
) t1
group t1.licence_no;