views:

810

answers:

6

hi i have a table with columns as

              Cost     Rate

              Repair   12
              Repair   223
              Wear     1000    
              Wear     666
              Fuel     500
              Repair   600
              Fuel     450
              Wear     400

Now i want this data as

             Repair    Wear   Fuel
               825     2066    950

Using Sql Query

Thanks in advance

A: 

You can use GROUP BY to combine results when using an aggregate function like SUM().

SELECT Cost, SUM(Rate) FROM MyTable GROUP BY Cost

This will return the results inverted from what you requested, but that shouldn't be a big deal I hope.

Cost     SUM(Rate)
---      ---
Repair   825
Wear     2066
Fuel     950
John Kugelman
+2  A: 
select sum(case when cost = 'Repair' then rate else null end) as Repair
, sum(case when cost = 'Wear' then rate else null end) as Wear
, sum(case when cost = 'Fuel' then rate else null end) as Fuel 
from CostRateTable
glasnt
Use WHEN instead of WHERE within the CASE syntax. And terminate a CASE with END or END CASE.
Bill Karwin
Ah, I was writing off the bat and didn't syntax checked. I'll fix it up, Cheers.
glasnt
A: 

select cost,sum(rate) from tablename group by cost

Prashanth
+1  A: 

The "rotation" you want (making rows into columns) can be obtained with SQL Server's PIVOT operator.

Alex Martelli
+1  A: 

I think that you're looking for a way to do Dynamic Pivoting or Dynamic Cross-Tabs.

Check these articles:

CMS
A: 

You can do this with a simple Crosstab query. There is a wizard in the Access Queries window that will walk you through creating one. Just click the New Query button and select the Crosstab Query Wizard.

Robert Harvey