2017-09-25 78 views
1

我使用學生數據並且有兩個具有相同結構但不同數據集的表。我想添加一個記錄爲'0'或'1'的新列,以確定學生是否出現在另一個表中。例如:SQL添加新列以檢查ID是否出現在另一個表中

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' 

或者這種性質的東西?我不能確定如何與聯接

回答

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 
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) 
0

你可以做到這一點

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

在這一點上LL在表1您的項目將是0,現在你只用1

UPDATE Table1 
SET NewColumn = 1 
WHERE ID IN (SELECT ID FROM Table2) 
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 
0

您可以使用LEFT JOIN

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 
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 
相關問題