有两张桌子。我想以这样的方式加入他们,我可以得到以下结果

时间:2016-03-16 05:37:37

标签: sql sql-server vb.net visual-studio-2010

student_mas::                  receipt_mas
name    class                   name     class     month
john     2nd                   john       2nd       JAN
bunny    3rd                   john       2nd       FEB
sunny    4th                   bunny      3rd       FEB

提交特定月份费用的学生将被插入第二个表格中,提及第二个表格中月份列中的月份 我想要那些没有提交JAN月费的学生名单 请帮我。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用 NOT EXISTS

<强>查询

select * from student_mas t
where not exists (
    select * from receipt_mas 
    where name = t.name
    and class = t.class
    and [month] = 'JAN'
);

<强> SQL Fiddle demo

答案 1 :(得分:1)

Ullas的答案会很完美但你可以尝试以下方法。

DECLARE @student_mas TABLE (
    NAME VARCHAR(50)
    ,class VARCHAR(10)
    );

insert into @student_mas 
values
('john', '2nd'),
('bunny', '3rd'),
('sunny', '4th');

DECLARE @receipt_mas TABLE (
    NAME VARCHAR(50)
    ,class VARCHAR(10)
    ,[month] VARCHAR(3)
    );

insert into @receipt_mas
values
('john', '2nd', 'JAN'),
('john', '2nd', 'FEB'),
('bunny', '3rd', 'FEB');

SELECT sm.*
FROM @student_mas sm
LEFT JOIN @receipt_mas rm ON sm.NAME = rm.NAME
    AND sm.class = rm.class
    AND rm.month = 'JAN'
WHERE RM.class IS NULL

答案 2 :(得分:0)

with student_mas as
(
SELECT 'JOHN' NAME,'2ND' CLASS FROM DUAL
union all
SELECT 'BUNNY' NAME,'3RD' CLASS FROM DUAL
union all
SELECT 'SUNNY' NAME,'4TH' CLASS FROM DUAL
)
select * from student_mas A
where not exists
(
    with receipt_mas as
    (
    SELECT 'JOHN' NAME,'2ND' CLASS,'JAN' MONTH FROM DUAL
    union all
    SELECT 'BUNNY' NAME,'3RD' CLASS,'FEB' MONTH FROM DUAL
    union all
    SELECT 'SUNNY' NAME,'4TH' CLASS,'FEB' MONTH FROM DUAL
    )
    select * from receipt_mas B
    where  A.NAME=B.NAME
    and    A.CLASS=B.CLASS
    and    B.MONTH='JAN'
)
/