我试图从我的表中获取不同的值。这是我的SQL查询
SELECT DISTINCT E.RM_Name, E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name,
E.SM_Mobile,E.Zone
from tbl_employee E where day(RM_DOB)=25 and month(RM_DOB)=6
这是我得到的输出:
RM_Name | RM_Mobile | ZSM_NAme |ZSM_Mobile | SM_Name | SM_Mobile |Zone
--------------|-------------| --------------|-----------| --------------| --------------|----------------
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |BULUNDSHAHAR
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |GHAZIABAD 1
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |MEERUT
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |MORADABAD
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |MUZAFFARNAGAR
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |NOIDA
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |SAHARANPUR
查询为除Zone以外的其他列提供重复值,因为它在此处不同。有没有办法得到像这样的输出:
RM_Name | RM_Mobile | ZSM_NAme |ZSM_Mobile | SM_Name | SM_Mobile |Zone
--------------|-------------| --------------|-----------| --------------| --------------|----------------
JOHNSON KYOSA | 1234567895 | Daniel GUPTA |1296541235 | KAPIL SHARMA | 2589631472 |BULUNDSHAHAR
即。如果除了Zone之外的所有其他行值相同,则显示一行(顶行)。 我尝试了以下查询,但它不起作用。
select * from tbl_employee where RM_Name in (
select RM_Name from tbl_employee WHERE day(RM_DOB)=25 and month(RM_DOB)=6
group by RM_Name having count(*) > 1
)
请建议我。谢谢!
答案 0 :(得分:2)
SELECT
E.RM_Name,E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name,E.SM_Mobile,MIN(E.Zone)
FROM
tbl_employee E
WHERE
day(E.RM_DOB)=25 and month(E.RM_DOB)=6
GROUP BY
E.RM_Name,E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name,E.SM_Mobile
答案 1 :(得分:1)
如果您一次只能返回1行,那么只需使用TOP
:
SELECT TOP 1 DISTINCT
E.RM_Name,
E.RM_Mobile,
E.ZSM_NAme,
E.ZSM_Mobile,
E.SM_Name,
E.SM_Mobile,
E.Zone
FROM tbl_employee E
WHERE day(RM_DOB)=25
AND month(RM_DOB)=6;
如果您要为多名员工做这件事,也许......
WITH RNs AS(
SELECT E.RM_Name,
E.RM_Mobile,
E.ZSM_NAme,
E.ZSM_Mobile,
E.SM_Name,
E.SM_Mobile,
E.Zone,
ROW_NUMBER() OVER (PARTITION BY E.RM_Name, E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name, E.SM_Mobile
ORDER BY E.Zone ASC) AS RN
FROM tbl_employee E
WHERE day(RM_DOB)=25
AND month(RM_DOB)=6)
SELECT *
FROM RNs
WHERE RN = 1;
答案 2 :(得分:0)
您可以使用row_number()
功能
select *
from (select *,
row_number() over (partition by RM_Name, RM_Mobile, ZSM_NAme, ZSM_Mobile, SM_Name, SM_Mobile order by Zone) Seq
from bl_employee t
where day(RM_DOB)=25 and month(RM_DOB)=6
) t
where Seq = 1;
答案 3 :(得分:0)
SELECT DISTINCT E.RM_Name, E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name,
E.SM_Mobile,E.Zone
from tbl_employee E where day(RM_DOB)=25 and month(RM_DOB)=6
group by E.RM_Name, E.RM_Mobile,E.ZSM_NAme,E.ZSM_Mobile,E.SM_Name,
E.SM_Mobile,E.Zone