让人对更多主题感兴趣 - Sql Server

时间:2015-06-15 12:07:59

标签: sql sql-server

对于这个主题感到抱歉,因为它不是非常明确的。我有2个表,一个存储人员数据,一个存储主题数据以及感兴趣的人。两个表如下所示

Id  Name
1   Imad
2   Sumeet
3   Suresh
4   Navin

受试者

Id  PId Subject
1   1   DC
2   1   DS
3   3   DS
4   4   CA

PId is a Persons' ID

我需要让所有对最大科目感兴趣的学生,例如Imad here。

这是我的查询

With c as
(
    select Pid, count(Id) as 'Total' from subjects group by Pid
)
select Pid into #Temp from c where Total = (Select Max(Total) from c)
select * from Person where Id in (Select Pid from #Temp)

它给了我期望的输出但是无论何时在面试中询问这种类型的问题,我从来没有得到面试官的良好反应,因为他们总是期望更好的解决方案。我对我的SQL技能没有信心,这就是为什么我认为必须有更有效的解决方案,因此我在这里发布了它。 谢谢

5 个答案:

答案 0 :(得分:5)

只需订购数据并获得最多一条带有关系的记录(这意味着如果某些学生的计数相同,他们都会得到结果):

select top 1 with ties p.Id, p.Name
from Subjects s
join Person p on s.PId = p.Id
group by p.Id, p.Name, 
order by count(*) desc

答案 1 :(得分:1)

你可以试试这个:

;With c as
(
    select Pid, count(Id) as 'Total' from subject group by Pid
)

select * from Person join c on c.Pid=Person.Id where c.total>1

答案 2 :(得分:0)

尝试这个

select * from person
    where id in(
    Select b.pid
    from subject b 
    group by b.pid
    having count(b.pid)>1
    )

答案 3 :(得分:0)

    declare @t table (ID int,name varchar(10))
    insert into @t (ID,name)values (1,'imad'),(2,'sumeet'),(3,'suresh'),(4,'navin')
    declare @tt table (Id int,Pid int,Subject varchar(10))
    insert into @tt (Id,Pid,subject)values (1,1,'DC'),(2,1,'DS'),(3,3,'DS'),(4,4,'CA')

 select p.ID,P.name,ttt.Subject from (Select P.ID,P.name,P.Cnt from (
select t.ID,t.name,COUNT((t.ID))Cnt from @t t
 INNER JOIN 
@tt tt ON t.ID = tt.Pid 
GROUP BY t.ID,t.name)P
GROUP BY P.Cnt,P.ID,p.name
HAVING(cnt) > 1)P
INNER JOIN @tt ttt ON Ttt.Pid = P.ID 

答案 4 :(得分:0)

TOP的当前解决方案是特定于MS SQL Server的。以下解决方案基于标准SQL的窗口化聚合函数,大多数DBMS支持这些函数:

select Pid, Total
from 
 (
   select Pid, count(Id) as Total
      ,rank() over (order by count(Id) desc) as rn
   from subjects group by Pid
 ) as dt
where rn = 1