我有一个查询,我正在寻找4个表的结果:客户端,客户计划,INSPLANS和CLIENTLOG 我的查询从表中提取了更多信息,但简化了如下:
select clients.name,
insplans.desc,
clientplans.group_no,
convert (varchar,clientlog.FNDATE,112) as LASTUPDATEDATE,
FROM
PROJECT.DBO.CLIENTS
join CLIENTPLANS
on clients.RECORD_ID = clientplans.CLIENT_ID
join INSPLANS
on insplans.RECORD_ID = clientplans.PLAN_ID
join CLIENTLOG
on clientlog.CLIENT_ID = clients.RECORD_ID
WHERE clients.record_id = clientplans.client_id
and clientplans.SEQUENCE_NUM < 2
我的问题是,当我加入CLIENTLOG
表时,我的结果会从3k气球中消失,预计会有33K重复数据。 clientlog
表显示对clients表进行的每次更新的条目。我只是想获得最后更新日期的记录。我知道我应该通过转换函数使用MAX,但我有一种感觉,我加入表的方式也是不正确的。如果有人能提供一些令人敬畏的澄清。
由于
答案 0 :(得分:0)
试试这个..
SELECT clients.NAME,
insplans.desc,
clientplans.group_no,
CONVERT (VARCHAR, clientlog.fndate, 112) AS LASTUPDATEDATE,
FROM project.dbo.clients
JOIN clientplans
ON clients.record_id = clientplans.client_id
JOIN insplans
ON insplans.record_id = clientplans.plan_id
JOIN (SELECT Max(fndate) FNDATE,
client_id
FROM clientlog
GROUP BY clientid) CLIENTLOG
ON clientlog.client_id = clients.record_id
WHERE clients.record_id = clientplans.client_id
AND clientplans.sequence_num < 2
答案 1 :(得分:0)
您可以使用MAX
添加获取最新的FnDate,您只需要将您选择的其他列添加到GROUP BY
子句中:
SELECT clients.name,
insplans.desc,
clientplans.group_no,
CONVERT(VARCHAR(8), MAX(clientlog.FNDATE), 112) AS LASTUPDATEDATE
FROM PROJECT.DBO.CLIENTS
INNER JOIN CLIENTPLANS
ON clients.RECORD_ID = clientplans.CLIENT_ID
INNER JOIN INSPLANS
ON insplans.RECORD_ID = clientplans.PLAN_ID
INNER JOIN CLIENTLOG
ON clientlog.CLIENT_ID = clients.RECORD_ID
WHERE clientplans.SEQUENCE_NUM < 2
GROUP BY clients.name,insplans.desc, clientplans.group_no;
这里实际上没有什么区别,但specify a length when declaring, or converting to a VARCHAR
是一种好习惯