我試圖連接兩個表,並從兩個表中選擇列,這些列基於哪裏約束條件以及分組條件。我遇到了一些我不明白的問題和行爲。我正在使用sybase。下面在兩個連接的表上使用GROUP BY BY HAVING
CREATE TABLE #test(
name varchar(4),
num int,
cat varchar(3)
)
CREATE TABLE #other(
name varchar(4),
label varchar(20)
)
Insert #test VALUES('a',2,'aa')
Insert #test VALUES ('b',2,'aa')
Insert #test VALUES ('c',3,'bb')
Insert #test VALUES ('a',3,'aa')
Insert #test VALUES ('d',4,'aa')
Insert #other VALUES('a','this label is a')
Insert #other VALUES ('b','this label is b')
Insert #other VALUES ('c','this label is c')
Insert #other VALUES ('d','this label is d')
SELECT t.name,t.num,o.label
FROM #other o inner JOIN #test t ON o.name=t.name
WHERE t.name='a'
GROUP BY t.name
HAVING t.num=MAX(t.num)
一個簡單的例子,我得到無感時,我有GROUP BY
(標籤列顯然與不同t.name)。如果我剪下GROUP BY
語句的查詢行爲與我所期望的,但後來我不得不用這個作爲一個子查詢,然後應用
SELECT * FROM (subquery here) s GROUP BY s.name having s.num=MAX(s.num)
必須有這樣做的更好的方法。任何幫助和解釋這種行爲將非常感激。
**我應該澄清。在我的實際查詢中,我有類似於 SELECT .... FROM(連接表)WHERE名稱IN(長名單),GROUP BY .....
由於'WHERE t.name ='a'',我不明白'GROUP BY t.name'的意思。請通過顯示輸出來澄清它。 – sarwar026