0

私はこのフォーラムに参加したばかりで、助けが必要です!

私のコードでは正しい結果が得られません。問題は、t140.BEL_GRLAG_AP の最大値を取得していないことです (これは、16 行目で行おうとしていることです)。SQLはまだ1人あたり2行以上を提供しますが、1人あたり1行、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
4

2 に答える 2

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
于 2012-08-08T19:01:07.653 に答える
0

使いたいと思いますGROUP BY

たとえば、次の 3 つの列があり、各組み合わせValue, ID, Tagの最大値を取得したい場合は、次のようにします。ValueID/Tag

SELECT MAX(Value), ID, Tag
FROM MyTable
GROUP BY ID, Tag
于 2012-08-08T18:44:14.730 に答える