Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

combinando o conjunto de resultados de muitas consultas selecionadas


Você pode usar CROSS JOINs para fazer isso.
CREATE TABLE table1 (id int, column1 varchar(5), column2 varchar(15));

CREATE TABLE table2 (column3 varchar(5), column4 varchar(15));

CREATE TABLE table3 (id int, column5 varchar(5), column6 varchar(15));

INSERT INTO table1 VALUES (1, 'aaa', 'row1')
INSERT INTO table2 VALUES ('bbb', 'table2')
INSERT INTO table3 VALUES (1, 'ccc', 'table3')
INSERT INTO table1 VALUES (1, 'ddd', 'table1')

SELECT * FROM (SELECT * FROM table1) a
           CROSS JOIN (SELECT * FROM table2) b 
           CROSS JOIN (SELECT * FROM table3) c

Resultado:
id    column1    column2   column3    column4    id    column5    column6
1     aaa        row1      bbb        table2     1     ccc        table3
1     ddd        table1    bbb        table2     1     ccc        table3

Atualização após esclarecimento:
CREATE TABLE table1 
(
        id int IDENTITY(1,1) 
        , searchstring nvarchar(25)
);

CREATE TABLE table2 
(
        id2 int IDENTITY(10, 10) 
        , searchstring2 nvarchar(25)
        , newsearchstring nvarchar(50)
);

CREATE TABLE table3
(
        id3 int IDENTITY(100, 100) 
        , id2 int
        , table3srow nvarchar(25)
)

INSERT INTO table1 VALUES ('something');
INSERT INTO table1 VALUES ('something else');
INSERT INTO table1 VALUES ('something'); -- ID = 3, this row will be selected by 1st query

INSERT INTO table2 VALUES ('something', 'newvalue1');
INSERT INTO table2 VALUES ('something else', 'this will not be shown');
INSERT INTO table2 VALUES ('something', 'this will be returned by query 2'); -- ID = 30, this row will be selected by 2nd  query

INSERT INTO table3 VALUES (10, 'not relevant');
INSERT INTO table3 VALUES (20, 'not relevant');
INSERT INTO table3 VALUES (30, 'This is from table 3'); -- This  row will be returned by 3rd query


SELECT * FROM 
    (SELECT TOP 1 id, searchstring FROM table1 WHERE searchstring = 'something'  and id =     (SELECT MAX(id) FROM table1 WHERE searchstring = 'something')) AS  query1,
    (SELECT TOP 1 id2, newsearchstring FROM table2 WHERE searchstring2 = 'something'  and id2 = (SELECT MAX(id2) FROM table2 WHERE searchstring2 = 'something')) AS  query2,
    (SELECT id2, table3srow FROM table3) as query3 
WHERE query3.id2 = query2.id2

Use a mesma abordagem para a tabela4 conforme indicado para a tabela3.