1

我无法同时使用 JOINS 和 group-by:我搜索了这个...但我没有找到解决方案..问题如下:

我有两个表,第一个是main_table字段eid,,,namestatus

第二个表是字段fid, eid, last_date,remarksnext_date

第二个表用于存储客户的后续详细信息(存储在 main_table 中的客户详细信息),我想获取每个客户的最后一个后续记录,其中包含选定的日期期间(从日期到 to_date),并按 next_date 降序排序。

我使用了以下查询但没有工作

SELECT * 
FROM main_table as MT 
JOIN followups as MF on MT.eid=MF.eid 
WHERE MT.status='open' AND MF.NDate<='2012-12-07' 
GROUP BY MF.eid 
ORDER BY MF.next_date DESC

提前谢谢...伙计们

4

3 回答 3

2

你可以尝试这样的事情:

select m.eid,
  m.name,
  m.status,
  f1.last_date,
  f1.remarks,
  f1.next_date
from maintable m
left join
(
  select max(last_date) maxLast, eid
  from followups
  where last_date between from_date and to_date
  group by eid
) f
  on m.eid = f.eid
left join followups f1
  on f.maxLast = f1.last_date
  and f.eid = f1.eid
where m.status='open'
  and f1.next_date<='2012-12-07'
order by f1.next_date desc
于 2012-12-07T12:03:37.180 回答
2

试试这个

SELECT * FROM main_table AS MT 
LEFT JOIN (SELECT * FROM (SELECT * FROM followups ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid 
WHERE MT.status='open' 
AND MF.NDate<='2012-12-07';
于 2013-06-01T10:34:10.760 回答
1

试试这个:

SELECT * FROM main_table AS MT 
LEFT JOIN (SELECT * FROM (SELECT * FROM followups WHERE NDate<='2012-12-07' ORDER BY next_date DESC) AS A GROUP BY eid) AS MF ON MT.eid=MF.eid 
WHERE MT.status='open';
于 2012-12-07T11:59:25.970 回答