Столбцы SQL Exclude и Move в левом внешнем соединении - PullRequest
0 голосов
/ 08 декабря 2010

Рассмотрим 2 таблицы

id  name
--------
1   abc
2   xyz
3   pqr

Table2:

id  type  name  title  fid
------------------------------------
1   123   qwer    mng   1
2   234   asdf    mng   1
3   234   asdfe   mng   2
1   123   qwert   mng   3

Прямо сейчас, когда я запрашиваю данные

DECLARE @table1 table (id int, name varchar(10))
INSERT INTO @table1
SELECT 1, 'abc'
UNION
SELECT 2, 'pqr'
UNION
SELECT 3, 'zxc'

DECLARE @table2 table (id int, name varchar(10), etype int, title varchar(10), fid int)
INSERT INTO @table2
SELECT 1, 'qwer', 123, 'mngr', 1
UNION
SELECT 2, 'asdf', 234, 'mngr', 1
UNION
SELECT 3, 'asdfe', 234, 'mngr', 2
UNION
SELECT 1, 'qwert', 123, 'mngr', 3



SELECT t1.Name as Emp, t2.name as Mg1, t2.title As Title1, t3.name as Mg2, t3.title as Title2
FROM @table1 t1
LEFT OUTER JOIN @table2 t2 ON t1.id = t2.fid AND t2.etype = 123
LEFT OUTER JOIN @table2 t3 ON t1.id = t3.fid AND t3.etype = 234

Я хочу изменить этот запрос, чтобы он изменил результат с

Emp        Mg1        Title1     Mg2        Title2
---------- ---------- ---------- ---------- ----------
abc        qwer       mngr       asdf       mngr
pqr        NULL       NULL       asdfe      mngr
zxc        qwert      mngr       NULL       NULL

до

Emp        Mg1        Title1     Mg2        Title2
---------- ---------- ---------- ---------- ----------
abc        qwer       mngr       asdf       mngr
pqr        asdfe      mngr
zxc        qwert      mngr       

Не уверен, как я могу достичь этого какие-либо идеи?

1 Ответ

1 голос
/ 08 декабря 2010
SELECT t1.Name as Emp, 
       coalesce(t2.name,t3.name) as Mg1, coalesce(t2.title,t3.title) As Title1, 
       case when t2.name is not null then coalesce(t3.name,'') else '' end as Mg2, 
       case when t2.title is not null then coalesce(t3.title,'') else '' end as Title2
FROM @table1 t1
LEFT OUTER JOIN @table2 t2 ON t1.id = t2.fid AND t2.etype = 123
LEFT OUTER JOIN @table2 t3 ON t1.id = t3.fid AND t3.etype = 234
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...