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 |
|
sangeeta
Starting Member
16 Posts |
Posted - 2006-12-11 : 17:36:56
|
| Hi -I am new to TSQL and any help on the following would be appreciated.I have a table that looks like thissecurity Message2345 Good2346 Gooduoas Badfsaf Moresdad Moreasdd Morendgs MoreI have to pull in a list of distinct messages with a count and any 3 cusips that belong to the message.I have written, something like thisSELECT MESSAGE_TEXT, COUNT(*) AS Expr1, MIN(security) AS Expr2, MAX(SECURITY) AS Expr3FROM dbo.DerivedSIACDataMessagesGROUP BY MESSAGE_TEXTORDER BY COUNT(*) DESCHowever, this lets me pull only 2 securities per message and I want to pull in 4 cusips.Any help would be apprecioatedThanks. |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-12-11 : 17:42:57
|
| [code]-- prepare test datadeclare @test table (security varchar(4), message varchar(4))insert @testselect '2345', 'Good' union allselect '2346', 'Good' union allselect 'uoas', 'Bad' union allselect 'fsaf', 'More' union allselect 'sdad', 'More' union allselect 'asdd', 'More' union allselect 'ndgs', 'More'-- do the workselect q.message, max(case when q.idx = 1 then security end) 'p1', max(case when q.idx = 2 then security end) 'p2', max(case when q.idx = 3 then security end) 'p3', max(case when q.idx = 4 then security end) 'p4'from ( select t1.message, t1.security, (select count(*) from @test t2 where t2.message = t1.message and t2.security <= t1.security) idx from @test t1 ) qgroup by q.messageorder by q.message[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
sangeeta
Starting Member
16 Posts |
Posted - 2006-12-12 : 10:01:05
|
| HI Peter.. thanks for your response. The problem that I face with your code is that my list of messages is huge and not fixed.Please advise. |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2006-12-12 : 10:20:11
|
Sigh...You only have to copy and run the code AFTER the line with "Do the work"!Copy the code to Query Analyzer and replace @test table name with the table name you use in YOUR environment.select q.message, max(case when q.idx = 1 then security end) 'p1', max(case when q.idx = 2 then security end) 'p2', max(case when q.idx = 3 then security end) 'p3', max(case when q.idx = 4 then security end) 'p4'from ( select t1.message, t1.security, (select count(*) from <YourTableNameHere> t2 where t2.message = t1.message and t2.security <= t1.security) idx from <YourTableNameHere> t1 ) qgroup by q.messageorder by q.message Peter LarssonHelsingborg, Sweden |
 |
|
|
sangeeta
Starting Member
16 Posts |
Posted - 2006-12-12 : 13:49:06
|
THansk a lot Peter. Really appreciate it. |
 |
|
|
|
|
|
|
|