SQL SERVER中两个表的日期比较

时间:2018-09-13 05:34:17

标签: sql-server

我有这个数据,

表一:

EmpID      Date          Absent
1          01/01/2018    1
1          01/02/2018    1
1          02/05/2018    1
1          03/25/2018    1
1          04/01/2018    0
1          05/02/2018    1
1          06/03/2018    1

表二

ID         Amount       DateEffective
1          5.00         02/06/2018
2          3.00         05/02/2018
3          10.00        06/03/2018

所需的输出

EmpID      Month       Year   Absent    Penalty
1          January     2018   2         5.00
1          February    2018   1         5.00
1          March       2018   1         3.00
1          April       2018   0         3.00
1          May         2018   1         13.00
1          June        2018   1         10.00

这是我的代码

SELECT { fn MONTHNAME(one.Date) } AS MonthName, YEAR(one.Date) AS Year, SUM(one.Absent) AS Absent,
    (
        SELECT top 1 two.DailyRate
        FROM table_two as two
        WHERE EmpID = '1'
        AND one.Date <= two.EffectivityDate
    )
FROM     table_one as one
WHERE    EmpID = '1'
GROUP BY { fn MONTHNAME(one.Date) }, MONTH(one.Date), YEAR(one.DTRDate)
ORDER BY Year(one.Date),month(one.Date)

并显示错误:

  

选择列表中的列“ one.Date”无效,因为该列未包含在聚合函数或GROUP BY子句中

请帮助解决此问题... 谢谢

2 个答案:

答案 0 :(得分:0)

尝试一下:

SELECT   
one.EmpID
,DATENAME(MONTH,one.Date)  AS [MonthName]
,YEAR(one.Date) AS [Year]
,SUM(one.Absent) AS [Absent]
,(SELECT top 1 two.Amount
    FROM table_two as two
    WHERE two.ID =  one.EmpID
    AND YEAR(two.DateEffective) >= YEAR(one.Date)
    AND MONTH(two.DateEffective) >=MONTH(one.Date)
) AS [Penalty]

FROM  table_one as one
WHERE    
   one.EmpID = '1'
GROUP BY one.EmpID,DATENAME(MONTH,one.Date), MONTH(one.Date), YEAR(one.Date)
ORDER BY Year(one.Date),month(one.Date)

答案 1 :(得分:0)

  

据我所知,

   select e.EmpID
   ,datename(month,e.Date)[month]
   ,year(e.Date) [year] 
   ,sum(e.Absent) as [Abscount]
   ,a.Amount 
   from 
   empl e  left join abs a 
   on datename(month,e.Date)=DATENAME(month,a.DateEffective)
   group by e.EmpID,DATENAME(MONTH,e.Date), MONTH(e.Date), YEAR(e.Date) , a.Amount
   order by Abscount desc
  

如果需要任何澄清,请回复我...