• jdr.suporte (1/31/2014)


    Try

    ;with

    T as (

    SELECT VendorCode, 1 as Seq, UnitPrice, Qty, (UnitPrice * Qty) as Total

    from Sales

    union

    SELECT VendorCode, 2, sum(UnitPrice), sum(Qty), sum(UnitPrice * Qty)

    from Sales

    group by VendorCode

    )

    SELECT case when Seq=1 then VendorCode else 'subtotal' end as VendorCode,

    UnitPrice, Qty, Total

    from T

    order by T.VendorCode, Seq;

    There's just no need to hit the table twice. Seriously, lookup WITH ROLLUP.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)