简体   繁体   中英

sql query select only one row from multiple rows

I have this query:

SELECT p.[PostingID]
      ,[EmployerID]
      ,[JobTitle]                  
      ,pin.[IndustryID]         
FROM [Posting] p
INNER JOIN [City] c
  ON p.CityID = c.CityID
LEFT OUTER JOIN PostingIndustry pin
  ON p.PostingID = pin.PostingID
WHERE (c.CityID = @CityId OR @CityId IS NULL) 
  AND (p.StateProvinceID = @StateProvinceId OR @StateProvinceId IS NULL) 
  AND (pin.IndustryID = @IndustryId OR @IndustryId IS NULL) 
  AND 
  (
     (p.[Description] LIKE '%' + @Keyword + '%' OR @Keyword IS NULL) 
     OR (p.[JobTitle] LIKE '%' + @Keyword + '%'  OR @Keyword IS NULL)
  ) 
  AND p.StreetAddress IS NOT NULL 
  AND p.ShowOnMap = 1

Which returns results for all the pin.[IndustryID] if IndustryId is not selected or if all the industries are selected. If only one industry is selected I am getting one result which is good, but when one posting is included in multiple industries then I am getting multiple results as on the image shown below:

在此处输入图片说明

So for example when thats happening I want to get only one result for that posting id otherwise I am getting multiple results for one google map marker per the image below: 在此处输入图片说明

Is there a way how I can optimize the query above to do what I need? Thanks in advance, Laziale

Try using a group by clause at the end

Use MAX(IndustryId) .

Then also

GROUP BY PostingId,EmployerId,Jobtitle

What about selecting only the row with the smallest IndustryId:

SELECT [PostingID]
      ,[EmployerID]
      ,[JobTitle]                  
      ,MIN(pin.[IndustryID])         
FROM [Posting] p
INNER JOIN [City] c
  ON p.CityID = c.CityID
LEFT OUTER JOIN PostingIndustry pin
  ON p.PostingID = pin.PostingID
WHERE (c.CityID = @CityId OR @CityId IS NULL) 
  AND (p.StateProvinceID = @StateProvinceId OR @StateProvinceId IS NULL) 
  AND (pin.IndustryID = @IndustryId OR @IndustryId IS NULL) 
  AND 
  (
     (p.[Description] LIKE '%' + @Keyword + '%' OR @Keyword IS NULL) 
     OR (p.[JobTitle] LIKE '%' + @Keyword + '%'  OR @Keyword IS NULL)
  ) 
  AND p.StreetAddress IS NOT NULL 
  AND p.ShowOnMap = 1
GROUP BY [PostingID],[EmployerID],[JobTitle] 

Whenever you have only one, it returns that one, when you have more than one it returns only the one with the smallest IndustryId.

不要选择行业ID并使用“ SELECT DISTINCT ...”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM