我正在尝试创建一些表格。我们的想法是为同一个名称显示所选的0 0r 1.name。如果值不是NULL,则为0,否则为1。
样本数据
表1
ID NAME
------------
1 Zebra
2 Monkey
3 Lion
4 Rabbit
表2
ID ID_table1 Name_table1
--------------------------
1 1 ZEBRA
2 3 Lion
3 3 Lion
4 1 Zebra
5 2 Monkey
6 3 Lion
7 4 Rabbit
如果我连接表并从表2中选择Id为2的值
RESULT
ID NAME Selected
---------------------
1 Zebra 0
2 Monkey 0
3 Lion 1
4 Rabbit 0
答案 0 :(得分:1)
需要使用LEFT JOIN
和CASE
SELECT T1.ID, NAME , case when T2.ID_Table1 is null then 0 else 1 end as value
FROM
Table1 T1
LEFT JOIN( select ID_table1
FROM Table2
where ID =2
) T2
on T1.ID = T2.ID_table1
答案 1 :(得分:0)
您不需要加入这两个表格。
您只能使用Table_2
执行此操作DECLARE @selected INT
SET @selected = 2
SELECT DISTINCT
id_table1 AS ID ,
name_table1 AS Name ,
SUM(CASE WHEN ID = @selected THEN 1
ELSE 0
END) AS selected
FROM Table_2
GROUP BY ID_Table1 ,
name_table1
ORDER BY id_table1
结果:
ID Name selected
1 ZEBRA 0
2 Monkey 0
3 Lion 1
4 Rabbit 0
答案 2 :(得分:0)
我在评论中提到的你应该使用COUNT()
SELECT t.ID, t.NAME, COUNT(t1.id_table1)
FROM Table1 t
LEFT JOIN
( SELECT ID_table1
FROM Table2
WHERE ID=2
)t1 ON t.ID = t1.ID_table1
GROUP BY t.id