sql >> Base de Datos >  >> Database Tools >> SSMS

Realizar unión en consultas unidas

su método actual no es muy eficiente. Otros generalmente usarán CASE WHEN para hacerlo.

SELECT   t.uniqueID,
         IN_Info1 = MAX(case when t.type = 'IN' then t.information1 end),
         IN_Info2 = MAX(case when t.type = 'IN' then t.information2 end),
         IN_Notes = MAX(case when t.type = 'IN' then t.Notes end),
         OUT_Info1 = MAX(case when t.type = 'OUT' then t.information1 end),
         OUT_Info2 = MAX(case when t.type = 'OUT' then t.information2 end),
         OUT_Notes = MAX(case when t.type = 'OUT' then t.Notes end)
FROM     TABLEB t
GROUP BY t.uniqueID

y luego para incorporar en su consulta grande, puede usar CTE o TABLA DERIVADA

-- CTE
; with Tblb as
(
  SELECT   t.uniqueID,
           IN_Info1 = MAX(case when t.type = 'IN' then t.information1 end),
           IN_Info2 = MAX(case when t.type = 'IN' then t.information2 end),
           IN_Notes = MAX(case when t.type = 'IN' then t.Notes end),
           OUT_Info1 = MAX(case when t.type = 'OUT' then t.information1 end),  
           OUT_Info2 = MAX(case when t.type = 'OUT' then t.information2 end),  
           OUT_Notes = MAX(case when t.type = 'OUT' then t.Notes end)
  FROM     TABLEB t
  GROUP BY t.uniqueID
)
select   *
from     TableA a
         inner join Tblb b ON a.uniqueID = b.uniqueID

No puedes hacer esto X1.t1.uniqueID. , solo debe ser X1.uniqueID