Sql 仅从主表中获取行

Sql 仅从主表中获取行,sql,sql-server,tsql,Sql,Sql Server,Tsql,表1: ID Year MatchNumber 0 0 0 1 2017 1 2 2017 2 3 2017 3 4 2017 4 5 2016 1 6 2016 2 7 2016 3 8 2016 4 9 2015 1 10 2015 2 11 2015 3 12 2015 4 13 2017 5 表2: Year MatchNumb

表1:

ID  Year    MatchNumber
0   0       0
1   2017    1
2   2017    2
3   2017    3
4   2017    4
5   2016    1
6   2016    2
7   2016    3
8   2016    4
9   2015    1
10  2015    2
11  2015    3
12  2015    4
13  2017    5
表2:

Year        MatchNumber
2017        1
2017        2
2017        3
2017        4
2016        1
2016        2
2016        3
2016        4
2015        1
2015        2
2015        3
2015        4
预期输出:基于案例条件 案例1:

如果Id为0,则为0

案例2如果Id为0,yeat和matchnumber匹配,则为1

其他2

ID     Year     MatchNumber   conditionMatched
0      0        0             0
1      2017     1             1
2      2017     2             1
3      2017     3             1
4      2017     4             1
5      2016     1             1
6      2016     2             1
7      2016     3             1
8      2016     4             1
9      2015     1             1
10     2015     2             1
11     2015     3             1
12     2015     4             1
13     2017     5             2
我还有一个表类别要包含在join中。 Categoryid CategoryName 0 X 1年 2 Z 改为基于硬代码0,1,2的标记;我需要加入类别表标记其值。

您有不同的情况吗? 所以用例语句:)

还有一种方法(可以从SQL Server 2012和SQL Server 2008开始使用):

在这里使用Case很好,但是当在第二个表中多次找到条目时,左连接可能会导致返回多行。使用上面提到的EXISTS结构可能更好

您的问题是什么。请参见“如何提问”。
SELECT  ID, 
        T1.[Year], 
        T1.MatchNumber, 
        CASE WHEN ID=0 THEN 0 
            WHEN T2.[year] IS NOT NULL THEN 1 
            WHEN T2.[year] IS NULL THEN 2 
                END AS conditionMatched
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 
    ON T1.[year]=T2.[year] AND T1.MatchNumber=T2.MatchNumber
ORDER BY ID;
SELECT  t.ID,
        t.[Year],
        t.MatchNumber,
        IIF(t.ID>0,2,0)-COALESCE(p.MatchNumber-t.MatchNumber+1,0)
FROM Table1 t
LEFT JOIN Table2 p
    ON t.[year] = p.[year] 
        AND t.MatchNumber = p.MatchNumber
ORDER BY t.ID
SELECT  [Value] = CASE WHEN EXISTS (SELECT 1 FROM Table2 t2 WHERE t2.[Year] = t1.[Year] AND t2.[MatchNumber] = t1.[MatchNumber])
        THEN 1
        ELSE 2
    END