0

I have been trying to combine without success using UNIONS and JOINS 4 tables. Each of this tables has just one column and 2 rows and they don't have anything in common. I am trying to create 1 Table that combines them all with all rows aligned.

Example:
Table 1
vegetables
Potato  
Tomato 

Table 2
Utilities
Knife
Pan

Table 3
Fruits
Orange
Apple

Table 4
Liquids
Wine
Water

Final Table:

vegetables  Utilities  Fruits   Liquids
Potato      Knife      Orange   wine 
Tomato      Pan        Apple    Water

Sorry for the weird names, and if this has already been asked. I tried several examples i found around but most of them use a common key to filter, but as the tables have nothing When I tried this examples I ended up with a table with 8 Rows The tables also can variate in amount of rows from 1 to 10, but they if one has 10 they all do.

Thanks in advance.

EDIT: I am using SQL server Express 2012

4

1 回答 1

3

试试这个——

查询一:

DECLARE @temp1 TABLE (vegetables NVARCHAR(50))
INSERT INTO @temp1 (vegetables)
VALUES ('Potato'), ('Tomato')

DECLARE @temp2 TABLE (Utilities NVARCHAR(50))
INSERT INTO @temp2 (Utilities)
VALUES ('Knife'), ('Pan')

DECLARE @temp4 TABLE (Liquids NVARCHAR(50))
INSERT INTO @temp4 (Liquids)
VALUES ('Wine'), ('Water')

DECLARE @temp3 TABLE (Fruits NVARCHAR(50))
INSERT INTO @temp3 (Fruits)
VALUES ('Orange'), ('Apple')

SELECT t1.vegetables, t2.Utilities, t3.Fruits, t4.Liquids
FROM (
    SELECT t.vegetables, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp1 t
) t1
JOIN (
    SELECT t.Utilities, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp2 t
) t2 ON t1.id = t2.id
JOIN (
    SELECT t.Fruits, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp3 t
) t3 ON t1.id = t3.id
JOIN (
    SELECT t.Liquids, id = ROW_NUMBER() OVER (ORDER BY (SELECT 1)) 
    FROM @temp4 t
) t4 ON t1.id = t4.id

输出 1:

vegetables  Utilities  Fruits   Liquids
----------- ---------- -------- ---------
Potato      Knife      Wine     Orange
Tomato      Pan        Water    Apple    

查询2(您评论的可能答案)

SELECT t1.vegetables, t2.Utilities, t3.Fruits, t4.Liquids
FROM @temp1 t1
CROSS JOIN @temp2 t2
CROSS JOIN @temp3 t3
CROSS JOIN @temp4 t4

输出 2:

vegetables   Utilities  Fruits    Liquids
------------ ---------- --------- -------
Potato       Knife      Wine      Orange
Potato       Knife      Apple     Orange
Potato       Knife      Wine      Water
Potato       Knife      Apple     Water
Tomato       Knife      Wine      Orange
Tomato       Knife      Apple     Orange
Tomato       Knife      Wine      Water
Tomato       Knife      Apple     Water
Potato       Pan        Wine      Orange
Potato       Pan        Apple     Orange
Potato       Pan        Wine      Water
Potato       Pan        Apple     Water
Tomato       Pan        Wine      Orange
Tomato       Pan        Apple     Orange
Tomato       Pan        Wine      Water
Tomato       Pan        Apple     Water
于 2013-05-15T12:41:11.210 回答