在这种情况下使用什么查询-sqlServer

时间:2019-05-30 14:10:26

标签: sql-server

我有2张桌子:

信息:

enter image description here

得分:

enter image description here

我可以使用哪个查询来获得此结果? (月份和年份栏显示了2019年6月球员的得分 enter image description here

2 个答案:

答案 0 :(得分:0)

您可以这样做

SELECT 
    Info.id
    , Info.Name
    , Info.age
    , DATEDIFF(MONTH, CAST(score.date AS datetime), GETDATE()) AS Moths
    , DATEDIFF(YEAR, CAST(score.date AS datetime), GETDATE()) AS Years
FROM 
    Info 
    INNER JOIN Score
    ON Info.id = Score.ID

答案 1 :(得分:0)

尝试以下操作:

select info.id, info.name,info.age, sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as monthS,sum(case when MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019 then score else 0 end) as  yearS
from info
inner join score
on info.id = score.id
group by info.id, info.name,info.age

OR:

select info.id, info.name,info.age, sum(isnull(score,0)) as monthS,sum(isnull(score,0)) as  yearS
from info
left join
(
    select * from score
    where MONTH(convert(datetime,score.date,5)) = 6 and Year(convert(datetime,score.date,5)) = 2019
 ) as s
on info.id = s.id
group by info.id, info.name,info.age

示例工作here