473,506 Members | 16,954 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pivot? rows to columns

5 New Member
Hi folks,
I have a table example:
Date Team Score
200801 A 12
200801 B 14
200802 A 3
200803 C 5
200803 A 5

Date and team are not hardcoded, next week team D could be added etc.

I'd like to convert (pivot?) to
Date A B C
200801 12 14
200802 3
200803 5 5

is there a simple approach to this?
any help appreciated. Sorry don't know what this type of conversion is called.

thanks.
Aug 19 '08 #1
7 8728
r035198x
13,262 MVP
Could you maybe explain what the result should represent?
Aug 19 '08 #2
ck9663
2,878 Recognized Expert Specialist
Maybe this helps.


-- CK
Aug 19 '08 #3
larry2
5 New Member
Maybe this helps.


-- CK
Yeah I've been reading through the online docs etc., and some nice books like 'SQL Cookbook' and 'the Art of SQL'. The problem with the example in the linked page is that '[164] as emp1 ... as emp2' the columns are hardcoded into the sql statement. Since the team in each row (A, B, C, etc.) will later include other teams, this won't work for me.

I can write some code to create new sql statements each time by a first pass to determine unique teams, then use a case statement, just thought there'd be a cleaner approach.
Aug 19 '08 #4
larry2
5 New Member
Could you maybe explain what the result should represent?
Sure!
The result is grouped by row.col1 (date), with row.col2 the new col1->n, and row.col3 the data.

If it helps, think of it as total points each month. In Jan Team A had 12 points. In Jan Team B had 14 points. In Feb Team A had 3. In March Team C joined and had 5 points. In March Team A had 5 points.

I don't want to hard code the teams into record columns as these will change over time and would require recoding. Could do T1->t20 etc. but that still forces limits, gotta recode for team 21.

Probably wasn't obvious from the previous message, here is the desired output again: Note I could end up with 1000's of records to process, maybe 20 or so teams. I added 0's instead of spaces to help display, either (0's or spaces) is okay.



Date__ | A | B | C |
200801 | 12 | 14 | 0 |
200802 | 3 | 0 | 0 |
200803 | 5 | 0 | 5 |
Aug 19 '08 #5
larry2
5 New Member
Well I'm about 90% there perhaps.

SELECT *
FROM
(Select TDate, Team, Score from Test) tts
PIVOT
(
SUM(Score) FOR Team IN (A,B,C)
) as pvt

Again only problem is the (A,B,C) I'm looking for a wildcard or something I can use here so I don't have to preselect the column names.

MS Access Wizard gave me this:
TRANSFORM Sum(Test.Score) AS SumOfScore
SELECT Test.TDate
FROM Test
GROUP BY Test.TDate
PIVOT Test.Team;

which doesn't require the columns names, but this doesn't translate to mssql.

Any other suggestions?
Aug 20 '08 #6
BHTanna
31 New Member
Try this store procedure..

CREATE PROCEDURE crosstab
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)
AS
DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS ON

if exists(select name from sysobjects where name = '##pivotos' and type= 'U')
DROP TABLE ##pivotos
Print('SELECT ' + @pivot + ' AS pivot INTO ##pivotos FROM ' + @table + ' WHERE 1=2')

exec ('SELECT ' + @pivot + ' AS pivot INTO ##pivotos FROM ' + @table + ' WHERE 1=2')



EXEC ('INSERT INTO ##pivotos SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')
SELECT @sql='',
@sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

--print(@sumfunc)

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivotos' AND column_name='pivot'

SELECT @sql=@sql + '''' + convert(varchar(100), pivot) + ''' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), pivot) + @delim + ' THEN ' ) + ', ' FROM ##pivotos

DROP TABLE ##pivotos

SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)
Aug 20 '08 #7
larry2
5 New Member
Try this store procedure..
...=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)
I get incorrect syntax near the keyword 'pivot', line 31, then 34

tried changing a few things (pivot to piv so not reserved word etc.) but sol.

Will take me a while to figure out what this routine is doing. I take it this is a generic procedure you use? Does it work as posted for you? I'm using MS SQL 2005
Aug 21 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
537
by: Michael John | last post by:
Dear Oracle Developers, my task is to make up a Oracle View from a Pivot table in MS Access. Given are two tables to join: T_FIRM: FIRM_ABBR VARCHAR2(3 BYTE), FIRM_LONG ...
4
2849
by: Alan Lane | last post by:
Hello world: I'm including both code and examples of query output. I appologize if that makes this message longer than it should be. Anyway, I need to change the query below into a pivot table...
4
11685
by: Ajay | last post by:
Hello all, I used to display reports in Excel earlier on my website. Now the client has requested that he would like see reports in Pivot table on the web . The backend is Sql2000. Can you please...
1
3128
by: Grey | last post by:
I have created a asp.net form for user to input data. After input the data, user need to click a button to export the input data to excel for data analysis with excel pivot table function. is it...
0
1710
by: Tim_k | last post by:
Does anyone have an example of how to export a datagrid to an Excel pivot table? The code below exports the grid contents to Excel using the Response object. I'd like to expand it to show the...
1
7332
by: kingster | last post by:
Hi, I have a regular dataset and all i want to do is make a pivot table display in a browser with the datasource of the pivot table to be this dataset and then the end-user will be able to do...
8
4832
by: Jerome Ranch | last post by:
Okay So I've got pivot tables setup in Access 2003. Only about 30K records in the current 2005 databases...the pivots summarize the info in a number of nice ways. I need to get the pivot tables...
9
6771
by: PeteCresswell | last post by:
I've got something called "Reference Rates". The idea is that on a given day, we have various rates of return for various entities. e.g. Libor 3-month return, Libor 6-month return, US Treasury...
9
101415
by: dotnetguru | last post by:
Hi SMART GUYS, Please help me write a query. Actually I want to convert my rows into columns. Can anyone kindly give me the query to do it? My rows are about employees. There can be any number of...
0
2214
by: das | last post by:
Hello all, I have tried this in SQL 2000 with no luck, with pivot table feature in 2005 I see some hope. Here is my problem, I have a table with n rows. data within these is simple varchar. I want...
0
7218
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7021
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7478
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5614
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
3177
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1532
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
409
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.