我有下表Employee和记录如下:
Eid Ename Phone
------------------------
1 A 043
1 A 067
2 B 073
2 B 072
3 C 753
3 C 464
到目前为止我得到了什么:
SELECT *
FROM (SELECT Row_number() OVER (ORDER BY Eid ASC) AS rownum,
Eid,
Ename,
Phone
FROM Employee
WHERE Eid IN(SELECT DISTINCT(Eid)
FROM Employee
GROUP BY Eid)) AS RESULTSET
WHERE rownum BETWEEN 0 AND 3
实际上,内部查询会返回distinct
结果,但是当我在最终RESULTSET
获得结果时,它不会反映出来。
请告知如何获得独特的结果。我的输出应该如下所示:
Eid Ename Phone
------------------------
1 A 043
2 B 073
3 C 753
答案 0 :(得分:2)
如果使用QUALIFY
子句,则可以指定要返回的Row_Number值范围。 QUALIFY
子句用于窗口聚合函数HAVING
子句与非窗口聚合函数的对比。
SELECT DISTINCT
e1.eid
, e1.ename
, e1.ephone
-- , ROW_NUMBER() OVER(PARTITION BY e1.eid ORDER BY e1.eid) AS RowNum_
FROM emp e1
QUALIFY ROW_NUMBER() OVER(PARTITION BY e1.eid ORDER BY e1.eid) = 1
如果您在结果集中包含RowNum_
,则可以在QUALIFY
而不是ROW_NUMBER()
窗口聚合中再次引用它。
答案 1 :(得分:2)
您的查询要复杂得多。尝试使用CROSS APPLY
SELECT DISTINCT a.Eid, a.Ename, c.Phone
FROM EMPLOYEE a
CROSS APPLY
(
SELECT TOP 1 ROW_NUMBER() OVER (PARTITION by Ename ORDER BY Eid ASC) AS RowNo,
b.Eid, b.Phone
FROM EMPLOYEE b
WHERE a.EID = b.eid
ORDER BY RowNo ASC -- you can change this to DESC also
) c
我添加DISTINCT
的原因是因为您要自己加入表格。
另一个更简单的版本
SELECT DISTINCT a.Eid, a.Ename, c.Phone
FROM EMPLOYEE a
CROSS APPLY
(
SELECT TOP 1 b.Eid, b.Phone
FROM EMPLOYEE b
WHERE a.EID = b.eid
) c
答案 2 :(得分:1)
啊,我不知道你想要这个查询,但不知怎的,我把它建在你的预期输出
代码:
select Eid,Ename,Phone
from (select ROW_NUMBER() OVER (ORDER BY Eid ASC) AS rownum,
Eid,
Ename,
Phone
from Employee
where Eid in (select distinct(Eid)
from Employee )
) AS RESULTSET
Where rownum %2<>0
答案 3 :(得分:0)
试试这个
SELECT *
FROM (SELECT Row_number() OVER (partition by ename ORDER BY Eid ASC) AS rownum,
Eid,
Ename,
Phone
FROM Employeee
WHERE Eid IN(SELECT DISTINCT(Eid)
FROM Employeee
GROUP BY Eid)) AS RESULTSET
WHERE rownum =1
答案 4 :(得分:0)
试试这个:
select Eid,Ename,Phone from
(select *,ROW_NUMBER() over(partition by Ename order by eid) as rn from emp) a
where rn=1