我正在尝试编写一个查询,它给出了execoffice_status = 1的记录数 (也可以等于= 0)。 我想通过使用一个不同的表员工来输出结果 名。
我写的查询似乎给了我一些结果,但给了我表中的所有记录 甚至在execoffice_status = 0的地方(不知道我将如何将其添加到查询中)。 我试图从查询中得到的是execoffice_status = 1的记录数 从哪一年(execoffice_date),最终我想从查询中得到的是前十名 每年(按年份排序)。
通过下面的查询,我得到所有记录,甚至execoffice_status = 0 查询:
SELECT *
FROM (
select ROW_NUMBER() OVER(PARTITION BY e.emp_namelast order by year(c.execoffice_date) desc ) as RowNum,
year(c.execoffice_date) as year, e.emp_nameFirst + ' ' + e.emp_namelast as fullname, count(c.execoffice_status) as stars
from phonelist.dbo.employee e
join intranet.dbo.CSEReduxResponses c on c.employee = e.emp_id
group by emp_namelast, emp_namefirst, year(c.execoffice_date)
) a
order by year
这是我用一些虚拟数据制作的http://sqlfiddle.com/#!3/79f253/1。
答案 0 :(得分:2)
对于你问题的第一点,你可以简单地添加一个where子句。
where c.execoffice_status=1
要获得每年的最高值,Rank
可以实现此目的:
SELECT *
FROM (
select RANK() OVER(PARTITION BY year(c.execoffice_date) order by e.emp_namelast desc ) as Rank,
year(c.execoffice_date) as year, e.emp_nameFirst + ' ' + e.emp_namelast as lastName, sum(c.execoffice_status) as stars
from employee e
join CSEReduxResponses c on c.employeee = e.emp_id
where c.execoffice_status=1
group by emp_namelast, emp_namefirst, year(c.execoffice_date)
) a
where rank <= 2
order by year
按用户的星号对用户进行编号,每年为您提供前2名。 (仅适用于10 <= 10
)
答案 1 :(得分:0)
以下是我理解您的要求的方式。
获取execoffice_status为1的每位员工每年的记录数 execoffice_status可以是一个或零
在这种情况下,你可以使用sum和group by,如果execoffice_status可以是1或0以外的其他数字,那么我们需要使用rownum和count,而不是sum和group by
请告诉我这是否符合您的要求。
select * from(
select a.employeEe,a.execoffice_date, SUM(a.execoffice_status) execoffice_status_count
from CSEReduxResponses a
group by a.employeEe,execoffice_date
) a
left outer join employee b
on b.emp_id = a.employeee
where EXECOFFICE_STATUS_COUNT > 0
order by execoffice_date desc;
如果你想得到前10行,我想用sql server你可以选择TOP 10 field1,field2,field3 from table
答案 2 :(得分:0)
SELECT * FROM (
select ROW_NUMBER() OVER(PARTITION BY e.emp_namelast order by year(c.execoffice_date) desc ) as RowNum,
year(c.execoffice_date) as year, e.emp_nameFirst + ' ' + e.emp_namelast as lastName, sum(c.execoffice_status) as stars
from employee e
join CSEReduxResponses c on c.employeee = e.emp_id
where c.execoffice_status <> 0
group by emp_namelast, emp_namefirst, year(c.execoffice_date)
) a WHERE RowNum<=10 order by year