我编写了一个SQL查询但是我收到错误
'company_name'附近的语法不正确。
我正在使用SQL Server 2005。
我的查询:
SELECT TOP 1
MONTH(a.dt_of_leave) MONTH,
YEAR(a.dt_of_leave) YEAR
FROM
emp_mst a
WHERE
MONTH(a.dt_of_leave) >= MONTH(getdate()) - 1
AND YEAR(a.dt_of_leave) = CASE
WHEN MONTH(getdate()) = 1
THEN YEAR(getdate()) - 1
ELSE YEAR(getdate()) company_name 'COMPANY NAME',
Deputed_Company_Name 'DEPUTED COMPANY NAME' emp_card_no 'EMP CODE',
emp_name 'EMPLOYEE NAME',
LWP,
'' Remarks,
Adj_Days Gain_Loss_LOP_Days,
VAL_DAY LOP_Days_Desc,
MONTH,
YEAR
FROM XXACL_EMP_INFO_LWP_OTDAYS_HRS_V WHERE emp_type='C'
AND MONTH = '3'
AND YEAR = '2016'
AND emp_card_no IN(312,
1250,
362)
更新
我有两个工作查询:
第一次查询
select top 1
month(a.dt_of_leave) month,
year(a.dt_of_leave) year
from
emp_mst a
where
month(a.dt_of_leave) >= month(getdate())-1
and year(a.dt_of_leave) = case
when month(getdate()) = 1
then year(getdate()) - 1
else year(getdate())
end
and emp_card_no IN (312, 1250, 362)
order by
emp_name
第二次查询:
select
company_name 'COMPANY NAME',
Deputed_Company_Name 'DEPUTED COMPANY NAME',
emp_card_no 'EMP CODE',
emp_name 'EMPLOYEE NAME',
LWP, '' Remarks,
Adj_Days Gain_Loss_LOP_Days,
VAL_DAY LOP_Days_Desc, month, year
from
XXACL_EMP_INFO_LWP_OTDAYS_HRS_V
where
emp_type = 'C'
and month = '3' and year = '2015'
and emp_card_no in (312, 1250, 362)
我想要的是第二次查询,我想添加从第一次查询得到的月份和年份。
我需要在第二个查询中合并
答案 0 :(得分:1)
尝试这样的事情 - 它将使用外部emp_card_no
子句中给出的三个WHERE
,并获取他们最近的月/年条目:
; WITH MonthAndYear AS
(
SELECT
MONTH(a.dt_of_leave) month,
YEAR(a.dt_of_leave) year,
emp_card_no,
RowNum = ROW_NUMBER() OVER (PARTITION BY emp_card_no ORDER BY dt_of_leave DESC)
FROM
emp_mst a
WHERE
MONTH(a.dt_of_leave) >= MONTH(GETDATE()) - 1
AND YEAR(a.dt_of_leave) = CASE
WHEN MONTH(GETDATE()) = 1
THEN YEAR(GETDATE()) - 1
ELSE YEAR(GETDATE())
END
)
SELECT
x.company_name 'COMPANY NAME',
x.Deputed_Company_Name 'DEPUTED COMPANY NAME',
x.emp_card_no 'EMP CODE',
x.emp_name 'EMPLOYEE NAME',
x.LWP, '' Remarks,
x.Adj_Days Gain_Loss_LOP_Days,
x.VAL_DAY LOP_Days_Desc,
x.month, x.year
FROM
XXACL_EMP_INFO_LWP_OTDAYS_HRS_V x
INNER JOIN
MonthAndYear my ON x.emp_card_no = my.emp_card_no
AND x.Month = my.Month AND x.Year = my.Year
AND my.RowNum = 1
WHERE
x.emp_type = 'C'
AND x.emp_card_no IN (312, 1250, 362);
我希望你能找到的是什么!如果没有 - 请分享表格结构,样本数据,预期输出等。