Search code examples
sqlsql-serversortingquerying

SELECT Only one value per ID - SQL Server


I dont know is this is possible at all, I´m not even sure how to google it.

Im using SQL Server 2014.

Right now I have a SP that outputs a table with data including MovementID, Vehicle, VehicleType and Total of sales. But it groups all the vehicles ids and vehicles types with a total.

I need to separate vehicles, which I can. The problem is that the totals appear duplicated, or triplicated etc.

So, how can I only select that column only one time per ID (MovementID in the example).

I'll keep trying, of course, but any idea would be appreciated.

[Example (Much more clear by looking at it)


Solution

  • You can use LAG to see values of the previous row.

    with q as (your query here)
    select 
      movementid, vehicleid, vecicletype, 
      case when movementid = lag(movementid) over (order by movementid, vehicleid)
        then null else total
      end as total
    from q
    order by movementid, vehicleid;