SQL添加一个新列以检查ID是否出现在另一个表中

时间:2017-09-25 20:25:29

标签: sql sql-server select case ssms

我使用学生数据并且有两个具有相同结构但不同数据集的表。我想添加一个记录为“0”或“1”的新列,以确定学生是否出现在另一个表中。例如:

Table 1:
s_id    s_year  s_term  s_crs       NewColumn(was student enrolled in 2016?)
123456  2017    Fall    Math 1010   1
654321  2017    Fall    Eng 1010    0

Table 2:
s_id    s_year  s_term  s_crs 
123456  2016    Fall    Math 2010
432516  2016    Fall    Eng 2010

你会怎么做呢?

SELECT s_id, s_year, s_term, s_crs 
(CASE 
    WHEN S_ID IN (select s_id from table2)
        THEN '1'

或那种性质的东西?我不确定如何用连接

来写这个

6 个答案:

答案 0 :(得分:1)

您可以left join使用第二个表,并查看结果列是否为空:

SELECT    t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 
          CASE WHEN t2.s_id IS NOT NULL THEN 1 ELSE 0 END AS newcolum
FROM      table1 t1
LEFT JOIN table2 t2 ON t1.s_id = t2.s_id

答案 1 :(得分:1)

假设表1是结果...仅使用基于s_id和s_year的子查询...如果有其他要求,请更新OP。

SELECT
  s_id,
  s_year,
  s_term,
  s_crs,
  ISNULL((SELECT
    1
  FROM table2 t2
  WHERE t2.s_id = t1.s_id
  AND t2.s_year = 2016), 0) [NewCol 2016]
FROM table1 t1

答案 2 :(得分:0)

假设s_id是一个常见的识别器

SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 1 as NewColumn
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM Table2 t2 WHERE t1.s_id = t2.s_id)
UNION 
SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 0 as NewColumn
FROM table1 t1
WHERE NOT EXISTS (SELECT 1 FROM Table2 t2 WHERE t1.s_id = t2.s_id)

答案 3 :(得分:0)

你可以这样做

ALTER TABLE Table1 ADD NewColumn BIT NOT NULL DEFAULT (0)

此时 Table1 中的所有项目都将为0,现在您只需用1

更新所需的项目
UPDATE Table1
SET NewColumn = 1
WHERE ID IN (SELECT ID FROM Table2)

答案 4 :(得分:0)

您可以使用左连接

SELECT    t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 
          CASE WHEN t2.s_Year = '2016' THEN 1 ELSE 0 END AS [NewColumn(was student enrolled in 2016?)]
FROM      table1 t1
LEFT JOIN table2 t2 ON t1.s_id = t2.s_id

答案 5 :(得分:0)

  create table #tbl1
  (
    s_id int,
    s_year varchar(4),
    s_term varchar(4),
    s_crs varchar (10)
  )

  insert into #tbl1 values(123456,'2017','Fall','Math 1010')
  insert into #tbl1 values(654321,'2017','Fall','Eng 1010')

  create table #tbl2
  (
    s_id int,
    s_year varchar(4),
    s_term varchar(4),
    s_crs varchar (10)
  )

  insert into #tbl2 values(123456,'2016','Fall','Math 2010');
  insert into #tbl2 values(432516,'2016','Fall','Eng 2010')


  select a.s_id,a.s_year,a.s_term,a.s_crs,case when b.s_id is null then '0' else '1' end as NewColumn
  from #tbl1 a left outer join #tbl2 b on a.s_id = b.s_id



  drop table #tbl1
  drop table #tbl2