より明確にするために更新
SQLSever2000。このクエリをもう少しユニークにしようとしています。
クエリ:
USE MyDatabase
GO
SELECT MAX(x.provider_entry_id) as provider_entry_id, -- this ID is the PK
x.provider_entry_type_id, -- the entry for the specific provider type (the ID)
x.provider_entry, -- the actual provider entry (the ID)
x.provider_entry_visit_dt -- the date the entry was created
FROM tbl_claimant_provider_entry x
JOIN (SELECT p.provider_entry_type_id,
p.provider_entry,
MAX(provider_entry_visit_dt) AS max_date
FROM tbl_claimant_provider_entry p
WHERE provider_entry_clmnt = 4963 -- change this for you user
GROUP BY p.provider_entry_type_id, p.provider_entry) y ON y.provider_entry_type_id = x.provider_entry_type_id
AND y.max_date = x.provider_entry_visit_dt
GROUP BY x.provider_entry_type_id, x.provider_entry, x.provider_entry_visit_dt
戻り値:
provider_entry_id provider_entry_type_id provider_entry provider_entry_visit_dt
1052 109 1088 2013-01-22 00:00:00.000
1051 109 1665 2013-01-23 00:00:00.000
1049 130 264 2013-01-01 00:00:00.000
1050 130 1126 2013-01-02 00:00:00.000
1045 132 NULL 2013-01-22 00:00:00.000
1047 132 260 2013-01-22 00:00:00.000
1044 132 1115 2013-01-10 00:00:00.000
1048 132 1130 2013-01-22 00:00:00.000
1043 142 1356 2013-01-10 00:00:00.000
このリストを絞り込んprovider_entry_type_id
で、最新のものに基づいて、それぞれの一意のインスタンスを1つだけ表示するようにしています。provider_entry_visit_dt
したがって、結果は次のようになります(provider_entry_visit_dtのタイブレーカーは必要ないことに注意してください。これは私の側のエラーです)。
provider_entry_id provider_entry_type_id provider_entry provider_entry_visit_dt
1051 109 1665 2013-01-23 00:00:00.000
1050 130 1126 2013-01-02 00:00:00.000
1048 132 1130 2013-01-22 00:00:00.000
1043 142 1356 2013-01-10 00:00:00.000