How to join several unrelated tables

爱⌒轻易说出口 提交于 2019-12-11 09:43:07

问题


I have five queries and each of them will return me single column multiple row output. I want to to write a function which will contain all of these queries.
Can anyone help?

query 1:

Select Col1 as X from Table1;

query 2:

Select Col3 as Y from Table2;

From a function I want to get a table which will have columns X, Y

How to club these queries under single function?


回答1:


Add a ROW_NUMBER() to each of the queries and join them by the row number. Depending on number of rows returned by each of the query you'd join then by inner, left or full join.

Example below assumes that two queries return the same number of rows.

WITH
CTE1
AS
(
    SELECT Col1 as X, ROW_NUMBER() OVER(ORDER BY Col1) AS rn
    FROM Table1
)
,CTE2
AS
(
    SELECT Col3 as Y, ROW_NUMBER() OVER(ORDER BY Col3) AS rn 
    FROM Table2
)
SELECT
    CTE1.X, CTE2.Y
FROM
    CTE1
    INNER JOIN CTE2 ON CTE1.rn = CTE2.rn



回答2:


Use the UNION operator:

SELECT
    column_1
FROM
    tbl_name_1
UNION ALL
SELECT
    column_1
FROM
    tbl_name_2;



回答3:


If there is a relation between the two tables, try using a join. Maybe a simple inner join would be possible here?

select Col1 as X from Table1
join 
on Table1.Col1_name = Table2.col3_name


来源:https://stackoverflow.com/questions/31452243/how-to-join-several-unrelated-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!