假設我有以下架構:
學生(姓名,兄弟姐妹)
相關表具有名稱和兄弟姐妹。請注意,同名的行數將與個人擁有的兄弟姐妹的數量相同。例如,一個表可能如下:
杰克、露
西杰克、蒂姆
這意味著杰克有露西和蒂姆作為他的兄弟姐妹。我想確定一個 SQL 查詢,該查詢報告所有有 2 個或更多兄弟姐妹的學生的姓名。我的嘗試如下:
select name
from student
where count(name) >= 1;
我不確定我在這個 SQL 查詢中是否正確使用了 count 。有人可以幫助確定正確的 SQL 查詢嗎?
uj5u.com熱心網友回復:
你快到了:
select name
from student
group by name
having count(*) > 1;
HAVING 是在分組完成后運行的 where 子句。在其中,您可以使用分組可以使用的東西(如計數和聚合)。通過對名稱進行分組并計數(過濾>1,如果你想要兩個或更多,而不是>=1因為這將包括 1)你得到你想要的名字..
這只會將“Jack”作為單個結果提供(在問題的示例資料中)。然后,如果您想要所有詳細資訊,例如 Jack 的兄弟姐妹是誰,您可以將分組的、過濾后的姓名串列加入表中:
select *
from
student
INNER JOIN
(
select name
from student
group by name
having count(*) > 1
) morethanone ON morethanone.name = student.name
您無法避免這樣做“重新加入”,因為分組已經丟棄了細節以創建組。獲取詳細資訊的唯一方法是獲取組給您的名單并使用它再次過濾原始詳細資訊資料
全面披露; 說“無法避免這樣做”有點撒謊:SQL Server 支持稱為視窗函式的東西,它可以在后臺有效地執行分組并將其連接回細節。這樣的查詢看起來像:
select student.*, count(*) over(partition by name) n
from student
對于這樣的表:
jack, lucy
jack, tim
jane, bill
jane, fred
jane, tom
john, dave
它會產生:
jack, lucy, 2
jack, tim, 2
jane, bill, 3
jane, fred, 3
jane, tom, 3
john, dave, 1
The rows with jack would have 2 on because there are two jack rows. There are 3 janes, there is 1 john. You could then wrap all that in a subquery and filter for n > 1 which would remove john
select *
from
(
select student.*, count(*) over(partition by name) n
from student
) x
where x.n > 1
If SQL Server didn't have window functions, it would look more like:
select *
from
student
INNER JOIN
(
select name, count(*) as n
from student
group by name
) x ON x.name = student.name
The COUNT(*) OVER(PARTITION BY name) is like a mini "group by name and return the count, then auto join back to the main detail using the name as key" i.e. a short form of the latter query
uj5u.com熱心網友回復:
你可以做:
select name
from student as s1
where exists (
select s2
from student as s2
where s1.name = s2.name and s1.siblings != s2.siblings
)
uj5u.com熱心網友回復:
我認為最好的方法是“Caius Jard”提到的。但是,如果您想獲取每個名稱有多少兄弟姐妹,還有另外一種方法。
SELECT name, COUNT(*) AS Occurrences
FROM student
GROUP BY name
HAVING (COUNT(*) > 1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422657.html
標籤:
