Sql-server – Selecting a group from groups based on one row condition

group byquerysql server

There is a group of rows which have the losscode and service odom. The contractnumber and service odometer are used to group the rows.

Please, may you help me to find the way to select only the row group which have the slosscode='REVSTD'?

enter image description here

Best Answer

I assume you want all rows of the group(s) where at least one row of the group has sLossCode = 'REVSTD'. In this case, you don't need GROUP BY. You can use either a self join (but that would only work under certain UNIQUE constraint requirements) or an EXISTS subquery:

SELECT s.sContractNumber, s.sLossCode, s.iServiceOdom
FROM service_table AS s
WHERE EXISTS
      ( SELECT 1
        FROM service_table AS q
        WHERE q.sLossCode = 'REVSTD'
          AND q.sContractNumber = s.sContractNumber
          AND q.iServiceOdom = s.iServiceOdom
      ) ;