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
 General SQL Server Forums
 New to SQL Server Programming
 PIVOT in SQL Server 2000

Author  Topic 

avmreddy17
Posting Yak Master

180 Posts

Posted - 2008-07-10 : 13:03:29
I have a table some thing like this

LiquidityFlag LastMkt LastQty
------------- -------------------------------- -----------
ADDED NSDQ 100
REMOVED ARCA 500
REMOVED NSDQ 100
REMOVED NSDQ 100
ROUTED ARCA 500
---

There are variuos diff LastMkts. Liquidityflag will just have
three Values ADDED , REMOVED and ROUTED



I want to O/P some thing like this.
Can some one please help

Destination ADDED REMOVED ROUTED
ARCA------------TOTALQTY---TOTALQTY---TOTALQTY
BATS
EDGX
EDGA
NSDQ

Thx
Venu

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-07-10 : 13:48:26
Hi.

THere is probably a much better way to do this but....


CREATE TABLE #prePivot (
[LiquidityFlag] VARCHAR(20)
, [lastMkt] CHAR(4)
, [lastQty] INT
)

CREATE TABLE #results (
[Destination] CHAR(4)
, [ADDED] INT
, [REMOVED] INT
, [ROUTED] INT
)

INSERT INTO #prePivot
SELECT 'ADDED', 'NSDQ', 100
UNION SELECT 'REMOVED', 'ARCA', 500
UNION SELECT 'REMOVED', 'NSDQ', 100
UNION SELECT 'REMOVED', 'NSDQ', 100
UNION SELECT 'ROUTED', 'ARCA', 500

-- Populate destination data
INSERT INTO #results (
[liquidityFlag]
)
SELECT DISTINCT
[lastMkt]
FROM
#prePivot

-- populate ADDED
UPDATE #results
SET
[ADDED] = a.[lastQty]
FROM
(
SELECT
[lastMkt] AS lastMkt
, SUM([lastQty]) AS lastQty
FROM
#prePivot
WHERE
[liquidityFlag] = 'ADDED'
GROUP BY
[lastMkt]
)
a
WHERE
a.[lastMkt] = #results.[Destination]


and repeat for the other columns in the same style as ADDED

-- I'm tired and unable to think so a better solution will not be coming from me.

All the best,

-------------
Charlie
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-07-10 : 13:57:51
you can do it like this

SELECT LastMkt AS Destination,
SUM(CASE WHEN LiquidityFlag='ADDED' THEN LastQty ELSE 0 END) AS ADDED,
SUM(CASE WHEN LiquidityFlag='REMOVED' THEN LastQty ELSE 0 END) AS REMOVED,
SUM(CASE WHEN LiquidityFlag='ROUTED' THEN LastQty ELSE 0 END) AS ROUTED
FROM Table
GROUP BY LastMkt
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2008-07-10 : 16:18:21
Yeah - do that, much better.

-------------
Charlie
Go to Top of Page

avmreddy17
Posting Yak Master

180 Posts

Posted - 2008-07-10 : 23:51:49
Thanks Guys
Go to Top of Page
   

- Advertisement -