我有一个Contract表,其中包含ContractTypeID,ContractID和ContractEndDate字段。一个ContractTypeID可以有多个ContractID,每个ContractID都有自己的ContractEndDate。
对于2016年与ContractEndDate签订合同的所有ContractTypeID,我有兴趣看到一个返回带有ContractTypeID和Result列的结果表的SQL查询。结果列应相应地读取:
答案 0 :(得分:0)
您可以使用大小写格式化答案并提取以在合同日期进行算术运算。发布你目前所拥有的内容,我愿意帮助你!
答案 1 :(得分:0)
将问题分解为部分以解决问题: (我建议你运行我在这里列出的每个查询,这样你就可以看到它是如何工作的。)
为感兴趣的年份制作标志
SELECT ContractID,
MAX(CASE WHEN YEAR(ContractEndDate) = 2016 THEN 1 ELSE 0 END) AS YEAR16,
MAX(CASE WHEN YEAR(ContractEndDate) = 2017 THEN 1 ELSE 0 END) AS YEAR17,
MAX(CASE WHEN YEAR(ContractEndDate) = 2018 THEN 1 ELSE 0 END) AS YEAR18
FROM Contract
GROUP BY ContractID
在此结果上使用您的逻辑:
SELECT ContractID,
CASE WHEN YEAR16 = 1 AND YEAR17 = 1 AND YEAR18 = 1 THEN
'Has a contract that ends next year and year after'
CASE WHEN YEAR16 = 1 AND YEAR17 = 1 THEN
'Has a contract that ends next year'
CASE WHEN YEAR16 = 1 THEN
'Has a contract that ends this year'
ELSE 'Something is wrong'
END
FROM (
SELECT ContractID,
MAX(CASE WHEN YEAR(ContractEndDate) = 2016 THEN 1 ELSE 0 END) AS YEAR16,
MAX(CASE WHEN YEAR(ContractEndDate) = 2017 THEN 1 ELSE 0 END) AS YEAR17,
MAX(CASE WHEN YEAR(ContractEndDate) = 2018 THEN 1 ELSE 0 END) AS YEAR18
FROM Contract
GROUP BY ContractID
) X