views:

36

answers:

2

I have a Order Details table.

What I want to do is create 1 query to show

OrderNumber | SKU | QTY | Price | Line Total |
1            SKU1    1    10.00        10.00
1            ----    0     0.00        10.00
2            SKU1    2    10.00        20.00
2            SKU2    3     1.50         4.50
2            ----    0     0.00        24.50

I mean I need to add another line for each order with total amount for export to text file.

I have SQL Server 2005

Thank you.

+1  A: 

I'm not sure if doing all that in a single SQL is a good idea, but you could try with a union:

SELECT *
FROM (
  SELECT ordernumber, sku, qty, price, qty*price line_total
  FROM order_details
  UNION
  SELECT ordernumber, '---' sku, 0 qty, 0 price, SUM(qty*price)
  FROM order_details
  GROUP BY ordernumber
)
ORDER BY ordernumber, sku

Have not tried this though.

Peter Lang
+3  A: 

The extra column is easy, just create another output column in the sql that is defined as the product of the two exsting attributes

  Select OrderNumber, SKU, QTY, Price, Qty * Price as  LineTotal
  From Table ...

The second part, adding a subtotal row, can be done with a keyword Rollup or by unioning with an aggregate query

  Select OrderNumber, SKU, QTY, Price, 
         Qty * Price as  LineTotal
  From Table 
  Union 
  Select OrderNumber, null SKU, null Qty, null Price, 
         Sum( Qty * Price ) as LineTotal
  From Table
  Group By OrderNumber
  Order By OrderNumber, Case When SKU Is Null then 1 Else 0 End
Charles Bretana