我试图连接两个表,并从两个表中选择列,这些列基于哪里约束条件以及分组条件。我遇到了一些我不明白的问题和行为。我正在使用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