使用2个表中的fileld选择最大值

时间:2015-06-11 07:54:27

标签: sql-server

我有一个数据库Library,它有很多表,我们需要3个表进行查询:

  • Librarians:ID,Surname;
  • 表格StudentCard:ID,桌面图书馆员的外键以及我们不使用的其他列
  • 表格TeacherCard:ID,桌面图书馆员的外键以及我们不使用的其他列

查询:选择图书管理员的姓氏,这个图书数量最多。

我知道,当我只从一张桌子拿走数据时,如何解决,e。 G。 TeacherCard

SELECT TOP 1 WITH TIES 
    Librarians.LastName, MAX(Librarians.CountOfBooks) AS Books 
FROM
    (SELECT 
         L.LastName, COUNT(*) AS CountOfBooks 
     FROM Libs L, T_Cards T
     WHERE T.Id_Lib IN (SELECT L.Id)
     GROUP BY L.LastName) AS Librarians
GROUP BY 
    Librarians.LastName
ORDER BY 
    MAX(Librarians.CountOfBooks) DESC
GO 

我不知道如何同时使用TeacherCardStudetnCard中的数据。

请帮助编写此查询。

2 个答案:

答案 0 :(得分:0)

我有正确的解决方法!!!!

SELECT TOP 1 B.Name, B.CountOut
FROM
(SELECT A.Name, SUM(A.Count) AS CountOut
FROM 
(SELECT Libs.LastName AS Name, COUNT(S_Cards.DateOut) AS [Count]
FROM Libs JOIN S_Cards ON S_Cards.Id_Lib = Libs.Id
GROUP BY Libs.LastName
UNION ALL
SELECT Libs.LastName AS Name, COUNT(T_Cards.DateOut) AS [Count]
FROM Libs JOIN T_Cards ON T_Cards.Id_Lib = Libs.Id
GROUP BY Libs.LastName) AS A
GROUP BY A.Name ) AS B
ORDER BY B.CountOut DESC

答案 1 :(得分:0)

我有另一个正确答案:

SELECT TOP 2 LastName, COUNT (*) [count] FROM
(SELECT LastName FROM Libs L, S_Cards S
WHERE S.id_lib = L.id
UNION ALL
SELECT LastName FROM Libs L, T_Cards T
WHERE T.id_lib = L.id) As Res
GROUP By LastName 
ORDER BY COUNT (*) DESC