列的最大值

时间:2012-08-08 18:38:09

标签: sql max

我是这个论坛的新手,需要一些帮助!

我的代码没有给出正确的结果。问题是我没有得到t140.BEL_GRLAG_AP的最大值(这是我在第16行中尝试做的)。 sql仍然为每个人提供两行或更多行,我只想要每人一行,一行有max(t140.BEL_GRLAG_AP)。

你们有谁能告诉我我失踪了吗? 任何帮助都很有意义!

select distinc tort128.NUM_AVTALE_ID as AvtaleID
, tort009.IDE_ARBGIV_NR as Orgnr
, tort134.NVN_ARBGIV as Arbeidsgiver
, mid(convert(varchar(8),tort127.DAT_KUNDE_FOEDT_NUM),7,2) + 
mid(convert(varchar(8),tort127.DAT_KUNDE_FOEDT_NUM),5,2) +
mid(convert(varchar(8),tort127.DAT_KUNDE_FOEDT_NUM),1,4) + 
RIGHT('00000' + TRIM(convert(CHAR(5),tort127.IDE_KUNDE_PRSNR)),5) as Fødselsnummer
, tort001.NVN_KUNDE_FOR + ' ' + tort001.NVN_KUNDE_ETTER as Navn
, tort140.NUM_ALDERSGRENSE as Aldersgrense

from tort128

join tort127 on tort128.IDE_SEKV_TORT127 = tort127.IDE_SEKV_TORT127
join tort001 on tort127.DAT_KUNDE_FOEDT_NUM = tort001.DAT_KUNDE_FOEDT_NUM and  tort127.IDE_KUNDE_PRSNR=tort001.IDE_KUNDE_PRSNR
join tort009 on tort127.DAT_KUNDE_FOEDT_NUM = tort009.DAT_KUNDE_FOEDT_NUM and   tort127.IDE_KUNDE_PRSNR=tort009.IDE_KUNDE_PRSNR
join tort134 on tort009.IDE_ARBGIV_NR = tort134.IDE_ARBGIV_NR
join tort138 on tort128.IDE_SEKV_TORT128 = tort138.IDE_SEKV_TORT128
left join tort140 on tort138.IDE_SEKV_TORT138 = tort140.IDE_SEKV_TORT138 
and tort140.BEL_GRLAG_AP=(select max(t140.BEL_GRLAG_AP) from tort140 t140
where 1 = 1
  and t140.IDE_SEKV_TORT138 = tort138.IDE_SEKV_TORT138)
and tort140.BEL_LOENN_AAR = (select max(t140_2.BEL_LOENN_AAR) from tort140 t140_2
where 1 = 1
  and t140_2.IDE_SEKV_TORT138 = tort138.IDE_SEKV_TORT138)

where

tort128.NUM_AVTALE_ID = 200854
and tort128.DAT_GYLDIG_FOM <= 20120101
and (tort128.DAT_GYLDIG_TOM >= 20120101
or tort128.DAT_GYLDIG_TOM is null)
and tort128.DAT_HISTORISK is null
and tort128.TYP_STATUS! = 'kns'
and tort127.DAT_KUNDE_FOEDT_NUM >= 19460101
and tort127.DAT_KUNDE_FOEDT_NUM <= 19551234
and tort127.DAT_TERMINERT is null
and tort127.DAT_REGISTRERT <= 20120101
and tort009.DAT_SLUTT is null
and tort134.DAT_HISTORISK is null
and tort138.DAT_AKSJON=(select max(p.DAT_AKSJON) from tort138 p
where 1 = 1
and p.IDE_SEKV_TORT128=tort128.IDE_SEKV_TORT128)

order by

tort127.DAT_KUNDE_FOEDT_NUM

2 个答案:

答案 0 :(得分:0)

我认为你想使用GROUP BY

例如,如果您有三列:Value, ID, Tag并想要获得每个Value组合的最大ID/Tag,那么您可以

SELECT MAX(Value), ID, Tag
FROM MyTable
GROUP BY ID, Tag

答案 1 :(得分:0)

如果您要加入不同的表格,那么您可以执行以下操作:

SELECT t1.ID, t2.id, t2.val
FROM table1 t1
INNER JOIN 
(
    SELECT Max(value) val, id
    FROM table2
    GROUP BY id
) t2
    ON t1.id = t2.id