当查询两个表(t1,t2)并对t2中的列使用MAX语句时,SQL会返回多个条目。
这似乎是因为我还从t2查询其他信息,其中包含唯一条目。
简化表格示例
t1.number t2.number_id t2.sync_id t2.text
1 1 1 'My problem is
1 1 2 That
2 2 3 Multiple entries
2 2 1 Are
2 2 2 Returned'
使用时
SELECT t1.number, max(t2.sync_id), convert(varchar(100),t2.text)
FROM t1, t2
WHERE t1.number = t2.number_id
GROUP BY t1.number, convert(varchar(100),t2.text)
我从示例表中获得了多个条目,而不仅仅是第2行和第5行。
答案 0 :(得分:2)
您需要从convert(varchar(100),t2.text)
中删除GROUP BY t1.number, convert(varchar(100),t2.text)
。现在,当您只想按t1.number
进行分组时,您现在按两个条件进行分组。
您也可能对如何将t2.text
列中的所有文本放在一行中感兴趣。如果是这样,请看一下:http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html
答案 1 :(得分:1)
至少假设SQL 2005,您可以使用CTE:
;with cteMaxSync as (
select t1.number, max(t2.sync_id) as MaxSyncId
from t1
inner join t2
on t1.number = t2.number_id
group by t1.number
)
select c.number, c.MaxSyncId, convert(varchar(100),t2.text)
from cteMaxSync c
inner join t2
on c.number = t2.number_id
and c.MaxSyncId = t2.sync_id
答案 2 :(得分:0)
标准SQL方法
SELECT
t1.number,
t2.sync_id,
convert(varchar(100),t2.text)
FROM
t1
INNER JOIN t2
ON t1.number = t2.number_id
INNER JOIN (
SELECT Max(t2.synch_id) synch_id, t1.number)
FROM t1
INNER JOIN t2
ON t1.number = t2.number_id ) max
ON t1.number = max.number and
t2.synch_id = max.synch_id