0

这是我的查询:

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。

4

2 回答 2

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
于 2012-10-17T09:42:05.673 回答
1

您必须使用聚合函数,例如inspection.inspection_date没有如下:mingroup bydistinct

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
于 2012-10-17T09:43:10.927 回答