2012-05-22 54 views
0

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

+0

由于'WHERE t.name ='a'',我不明白'GROUP BY t.name'的意思。请通过显示输出来澄清它。 – sarwar026

回答

0

如果我理解了您的查询得好。

SELECT t.name,t.num,o.label 
FROM #other o inner JOIN #test t ON o.name=t.name 
WHERE t.name='a' AND t.num=MAX(t.num) 
+0

问题是我想要每个t.name的最大值(t.num)。我知道自从这里做了很多,因为我在做t.name ='a',但在我的实际查询中我有t.name('大字母列表') – JPC

0

您的GROUP BY必须包含t.name,t.num和o.label。如果你这样做

GROUP BY t.name, t.num, o.label 

然后查询执行没有错误。

但是,您并未计算组中的任何聚合值。
你想做什么?

+0

这是一个简单的例子我正在努力。在我的实际查询中,我试图为每个t.name – JPC

+0

@jpc获取最新的日期记录(即max t.num):请参阅John Dewey的答案,是您需要的吗? – Phil

0

如果我正确理解你的要求,运行此...

SELECT t.name, num=MAX(t.num), o.label 
FROM #other o 
INNER JOIN #test t ON o.name=t.name 
WHERE t.name='a' 
GROUP BY t.name, o.label; 

......给了我这样的结果:

name num   label 
---- ----------- -------------------- 
a 3   this label is a 
+0

我不认为我正确表达了我的问题。我道歉。基本上,我使用GROUP BY名称HAVING num = MAX(num)的原因并不是真的,因为我需要实际的MAX(num),而是因为与该特定记录相关的数据是我想要的。我的实际项目涉及各种因素的各种实体的时间序列数据,所以我想检索每个特定实体的最新日期(在我的简化示例中,名称是实体,数字是日期)。但我还希望在之前的where子句和选择列来引用来自2个连接表中的列。 – JPC