Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Rowan Evans
Starting Member
2 Posts |
Posted - 2009-04-01 : 20:56:31
|
I have an existing data base that has the following informationJob Number___Trade__________Hours 23424______Electrician_______1023424________Rigger___________523424________Fitter___________8I am trying to write a query that will put it into the following formJob Number___Electrician___Rigger___Fitter23424___________10_________5________8PLease help!Thanks Rowan |
|
zzzbla
Starting Member
13 Posts |
Posted - 2009-04-03 : 01:32:31
|
Hi Rowan,Are the columns in the desired resultset fixed? Which version SQL Server are you using?If the columns are fixed and you use SQL Server 2005, you could use PIVOT to get the resultset you want:select *from (select jobnumber, trade, hoursfrom tblName) tPIVOT ( SUM(hours) FOR trade IN ([electrician],[rigger],[fitter]) ) AS pvtIf you're on 2000, you'll have to use the more complex looking syntax:SELECT jobnumber,sum(CASE WHEN trade='electrician' then hours else 0 end) AS [electrician],sum(CASE WHEN trade='rigger' then hours else 0 end) AS [rigger],sum(CASE WHEN trade='fitter' then hours else 0 end) AS [fitter]from tableNamegroup by jobnumberIf you don't know the columns (that is, all the trades) in advance, then you'll have to write a query that dynamically generates a query like the ones above, or use pivoting/cross tab features in the client application (available in Excel or Reporting Services for example).Cheers,S. Neumann |
|
|
Rowan Evans
Starting Member
2 Posts |
Posted - 2009-04-03 : 02:05:26
|
Thanks for the reply.I am not sure what version of SQL server i am using. Probably a stupid question but how do you find out? I am not even sure that i posted in the right area. I am building my query in Microsoft Query.Regards,Rowan |
|
|
zzzbla
Starting Member
13 Posts |
Posted - 2009-04-03 : 06:41:16
|
Microsoft Query in excel?As I wrote in my previous post you could use Excel Crosstab in order to accomplish the same thing.You can check SQL version with the query: SELECT @@VERSIONYou could also simply execute the queries from my previous post (don't forget to change "tableName" to your table name) - the first one will execute only on SQL 2005 and above.Hope that helps,S. Neumann |
|
|
|
|
|
|
|