table1 id col1 col2 col3... table2 col_id col_name 3432 col1 5342 col2 6756 col3
现在我想生成如下表3: id col_name col_value col_id
请注意col1,col2,col3 ......不按顺序排列。因此我必须查询table2以获取col_id(我认为pivot在这里不起作用)
如何在SQL中执行此操作?
答案 0 :(得分:0)
您似乎想要一个像这样的选择:
SELECT t2.id,
CASE
WHEN t2.col_name='col1' THEN t1.col1
WHEN t2.col_name='col2' THEN t1.col2
WHEN t2.col_name='col2' THEN t1.col2
-- ... more columns
ELSE NULL
END
FROM table2 t2 LEFT JOIN table2 t1 ON t2.col_id = t1.id
你也可以创建一个函数,虽然这在实践中会变慢:
CREATE OR REPLACE FUNCTION table1_col(id integer, name text) RETURNS text as $$
DECLARE
col_val text;
BEGIN
EXECUTE format('SELECT %s FROM table1 WHERE id=$1', name)
INTO col_val
USING id;
RETURN col_val;
END;
$$ LANGUAGE plpgsql;
SELECT table1_col(col_id,col_name) FROM table2;