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.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Crosstab...of sorts

Author  Topic 

snaayk
Starting Member

17 Posts

Posted - 2004-09-01 : 02:41:26
I'm looking for the best way to run a query that returns a crosstab. The problem is the columns are not based on a single column. In other words, depending on the particular column the criteria is using 4 or 5 columns for the correct count.

All the data is stored in a table which currently has about 550K rows. I currently run a sproc everytime the table is upated (once a day) that builds a summary table. Like this

SELECT COALESCE(fname, id), tb1, tb2, tb3, tb4
FROM employees right outer join
(select count(*) as tb1, id from table source where .... group by id) a
on employees.fid = a.id inner join
(select count(*) as tb1, id from table source where .... group by id) b
on a.id = b.id inner join
.... I do this 14 times

Every derived table provides a count of a particular set of criteria, they should all be joined by using the same id
The problem is I might not have a match in the employees table, in which case I want to use the id from any of the source tables. Originally I had inner joins from all the derived tables to the first table ('a'), but if the id did not exist in the 'a' table I lose the data from the rest of the tables. Outer joins provided even wacker results. I'm losing data at the more granular levels because not every id has a count for every generated column - i'd like nulls or 0's in this case.

I'm currently considering the following:

Selecting distinct id's from the source tables, and using nested subqueries.
SELECT fid, (SELECT COUNT(*) FROM source WHERE id=fid and...) as result1, (SELECT COUNT(*) FROM source WHERE id=fid and...) as result2, .... (14 times).
That seems rather intensive.

Or perhaps correlated tables

SELECT distinct s.id, tb1, tb2, tb3
FROM source s, (select count(*) from source where souce.id=s.id...) tb1, (select count(*) from source where source.id=s.id)tb2, ...

Who do the gurus here think? Which option or is there another option I'm not considering? I'm hoping to get some suggestions before venturing into QA experimentation

mk_garg20
Constraint Violating Yak Guru

343 Posts

Posted - 2004-09-01 : 02:48:47
here you go
http://www.sqlteam.com/item.asp?ItemID=2955

mk_garg
Go to Top of Page
   

- Advertisement -