表1
ID | NAME | INDICATOR |
-----------------------------------
0001 Item1 Y
-----------------------------------
0001 Item2 N
-----------------------------------
0006 Item3 N
-----------------------------------
0004 Item4 N
-----------------------------------
0004 Item5 N 表2
ID INDICATOR
--------------------
0001 Y
---------------------
0002 Y
---------------------
0003 Y
---------------------
0004 Y
---------------------
0005 N 首先,我需要在表2中选择其指示符为Y的id,然后使用该选择,我必须在表2中选择其指示符为N的名称和id,
标准:
如果table2的Id不存在于table1中,那么我的选择应该返回一个值,表示名称为NOTDEFINED,而Id在table1中没有Y。
输出必须是
ID | NAME
-----------------------
0001 Item1
------------------------
0002 NOTDEFINED
------------------------
0003 NOTDEFINED
------------------------
0004 NOTDEFINED 是否可以这样写一个select查询,如果有这样的帮助。
发布于 2017-05-08 12:25:44
根据所使用的后端,所需的SQL将有所不同。例如,在MS SQL server中:
select a.id,
case when Indicator = 'N' then 'NOTDEFINED' else a.name end as Name
from tableA a
where exists (select * from tableB b where a.ID = b.ID and b.Indicator = 'Y');发布于 2017-05-08 12:25:29
尝试以下查询:
SELECT t2.ID ID, IF(t1.name <> NULL, t1.name, 'NOTDEFINED') NAME FROM Table2 t2 LEFT JOIN Table1 t1 ON (t2.ID = t1.id AND t1.INDICATOR = 'Y') GROUP BY t2.ID发布于 2017-05-08 12:26:42
如果您想要表1中指示符为Y的名称,请使用示例1,否则,示例2应返回所要求的内容。
--Example 1
select table2.ID, isnull(table1.Name,'NOTDEFINED') from table2
inner join table1 on table2.ID = table1.ID
where table2.Indicator = 'Y' and table1.Indicator = 'N'
--Example 2
select table2.ID, isnull(table1.Name,'NOTDEFINED') from table2
inner join table1 on table2.ID = table1.ID
where table2.Indicator = 'Y' and table1.Indicator = 'Y'https://stackoverflow.com/questions/43847419
复制相似问题