Pulling back a distinct column

  • --Basically this query pulls back all the outstanding invoices for sold cars, the main issue I am having is that there can be more than one car on an invoice. In that case what I need to achieve is just pull back just one of these rows because the value outstanding on the invoice stays the same.Here is an example of an invoice with more than one vehicle. So I would just be looking to pull back the top row for this invoice. The query itself pulls back 380 rows with all invoices.

    SELECT vehicle.platenr, 'invoicefm' as Company, Invoice_FM.ClientId, client.Name,invoice_fm.Invoice_id as Document_Nr,Invoice_FM.Invoice_Date,Invoice_FM.Paid, Total_Value as AllValues

    FROM Invoice_FM inner join Client on Invoice_FM.ClientId = Client.ClientID left join vehicle on Invoice_FM.Invoice_id = vehicle.Invoice_Nr

    where Invoice_FM.deleted = 0

    and client.type_client = 'Fleet' order by Document_Nr

    Platenr Company Client Name Document_NR Date Value

    10D1234 invoicefm 213BRENNAN 18 2012-03-03 1 49000.00

    11D4321 invoicefm 213BRENNAN 18 2012-03-031 49000.00

    11D2123 invoicefm 213BRENNAN 18 2012-03-03 1 49000.00

  • Without knowing the structure of all your tables and data its difficult to help, this may point you in the right direction (untested as no consumable data):

    SELECT

    Qry.platenr

    , 'invoicefm' AS Company

    , Qry.ClientId

    , Qry.Name

    , Qry.Invoice_id AS Document_Nr

    , Qry.Invoice_Date

    , Qry.Paid, Qry AS AllValues

    FROM

    (

    SELECT

    *

    ,ROW_NUMBER() OVER (PARTITION BY Invoice_FM .DOCUMENT_NR ORDER BY vehicle .Platenr) AS RowNum

    FROM

    Invoice_FM

    INNER JOIN Client

    ON Invoice_FM.ClientId = Client.ClientID

    LEFT JOIN vehicle

    ON Invoice_FM.Invoice_id = vehicle.Invoice_Nr

    WHERE Invoice_FM.deleted = 0

    AND client.type_client = 'Fleet'

    ) AS Qry

    WHERE

    Qry.RowNum = 1

    ORDER BY Document_Nr

    Andy

    ==========================================================================================================================
    A computer lets you make more mistakes faster than any invention in human history - with the possible exceptions of handguns and tequila. Mitch Ratcliffe

  • The top row by what? Age of vehicle? Price of vehicle? Date vehicle added to invoice? Please also provide some table DDL and sample data.

    John

  • Cheers andy, that worked a treat. learning all the time. Thanks.

  • Your Welcome

    ==========================================================================================================================
    A computer lets you make more mistakes faster than any invention in human history - with the possible exceptions of handguns and tequila. Mitch Ratcliffe

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply