这是我的问题:
SELECT DISTINCT TOP 500
bk.firstname,
bk.surname,
bk.email,
county.region_id,
inspection.inspection_date
FROM
bken bk
LEFT OUTER JOIN county
ON bk.county = county.code
LEFT OUTER JOIN inspection
ON bk.inspid = inspection.inspid
WHERE
bk.firstname IS NOT NULL
AND bk.surname IS NOT NULL
AND bk.email IS NOT NULL
AND county.region_id IS NOT NULL
AND county.region_id <> 10
AND inspection_date > '04/01/2012 00:00:00.000'
AND inspection_date < '10/01/2012 00:00:00.000'
我的目标是获得500名不同人的样本。
不幸的是,这会返回重复的名称(虽然检查日期不同)所以我试图选择不同的姓氏,看看这是否能解决我的问题。任何人都可以帮我这样做吗?
我正在使用Microsoft SQL Server 2008。
答案 0 :(得分:2)
使用group by
:
SELECT TOP 500
bk.firstname,
bk.surname,
bk.email,
county.region_id,
max(inspection.inspection_date)
FROM
bken bk
LEFT OUTER JOIN county
ON bk.county = county.code
LEFT OUTER JOIN inspection
ON bk.inspid = inspection.inspid
WHERE
bk.firstname IS NOT NULL
AND bk.surname IS NOT NULL
AND bk.email IS NOT NULL
AND county.region_id IS NOT NULL
AND county.region_id <> 10
AND inspection_date > '04/01/2012 00:00:00.000'
AND inspection_date < '10/01/2012 00:00:00.000'
GROUP BY
bk.firstname,
bk.surname,
bk.email,
county.region_id
答案 1 :(得分:1)
您必须使用inspection.inspection_date
的{{1}}汇总函数,min
group by
而不distinct
,如下所示:
SELECT TOP 500
bk.firstname,
bk.surname,
bk.email,
county.region_id,
min(inspection.inspection_date) as inspection_date
FROM
bken bk
LEFT OUTER JOIN county
ON bk.county = county.code
LEFT OUTER JOIN inspection
ON bk.inspid = inspection.inspid
WHERE
bk.firstname IS NOT NULL
AND bk.surname IS NOT NULL
AND bk.email IS NOT NULL
AND county.region_id IS NOT NULL
AND county.region_id <> 10
AND inspection_date > '04/01/2012 00:00:00.000'
AND inspection_date < '10/01/2012 00:00:00.000'
group by bk.firstname,
bk.surname,
bk.email,
county.region_id