X Number Of Rows Into One Row Based On One Column - sql

I have been asked to display X number of rows, into a row that is going across with results. So for example :-
The Data
Tency Number| ClientNo | Name | DOB | Prim Client | Rent
10001 20 Joe 01/10/1900 Y 100
10001 21 bob 01/10/1901 N 100
10001 26 jim 01/10/1902 n 100
The format the user would like is
Tency Number | ClientNo | Name | DOB | Prim Client | Rent | Client2 | DOB 2|
10001 20 Joe 01/10/1900 Y 100 | Bob 01/10/1901 | Jim | 01/10/1902
We haven't got a pre defined number of client linked to Tenacy Number. I'm lost at what to use to achieve this. There is nothing there to pivot the table, and I used STUFF to link all the client into one column on the row (But they didn't want that).
Is this possible? And if so how would I achieve it?
Thank you!

The SQL you would need would be something like:
SELECT TencyNumber,
ClientNo = MIN(CASE WHEN RowNum = 1 THEN ClientNo END),
Client1 = MAX(CASE WHEN RowNum = 1 THEN Name END),
DOB1 = MAX(CASE WHEN RowNum = 1 THEN DOB END),
Client2 = MAX(CASE WHEN RowNum = 2 THEN Name END),
DOB2 = MAX(CASE WHEN RowNum = 2 THEN DOB END),
Client3 = MAX(CASE WHEN RowNum = 3 THEN Name END),
DOB3 = MAX(CASE WHEN RowNum = 3 THEN DOB END)
FROM ( SELECT TencyNumber,
ClientNo,
Name,
DOB,
PrimClient,
Rent,
RowNum = ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name)
FROM T
) c
GROUP BY TencyNumber;
But since you have an unknown number of clients, you would need to build the SQL dynamically:
DECLARE #SQL NVARCHAR(MAX) = '';
SELECT #SQL = #SQL +
',Client' + RowNum + ' = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN Name END)
,DOB' + RowNum + ' = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN DOB END)'
FROM ( SELECT RowNum = CAST(ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name) AS VARCHAR(10))
FROM T
) c;
SET #SQL = 'SELECT TencyNumber, ClientNo = MIN(CASE WHEN RowNum = 1 THEN ClientNo END) ' + #SQL + '
FROM ( SELECT TencyNumber,
ClientNo,
Name,
DOB,
PrimClient,
Rent,
RowNum = ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name)
FROM T
) c
GROUP BY TencyNumber;';
EXECUTE SP_EXECUTESQL #SQL;
Example on SQL Fiddle

Related

SQL Transpose row to columns

I am trying to transpose rows to columns but I didn't find any good answers.
Here is an example of what I want:
Input tables:
TABLE A
ID | NAME
1 | BOB
2 | JIM
3 | ROB
TABLE B
ID | CLUB
1 | 2
1 | 3
1 | 4
2 | 2
2 | 1
3 | 5
OUTPUT will be:
ID | CLUB1 | CLUB2 | CLUB3
1 | 2 | 3 | 4
2 | 2 | 1 |
3 | 5 | |
You need to enumerate the values to pivot them:
select id,
max(case when seqnum = 1 then club end) as club_1,
max(case when seqnum = 2 then club end) as club_2,
max(case when seqnum = 3 then club end) as club_3
from (select b.*,
row_number() over (partition by id order by club) as seqnum
from b
) b
group by id;
use conditional aggregation
select id,
max(case when id=1 then club end) club1,
max(case when id=2 then club end) club2,
max(case when id=3 then club end) club3
from tablename
group by id
use case when
select a.id,max(case when name='BOB' then CLUB end) ,
max(case when name='JIM' then CLUB end),
max(case when name='ROB' then CLUB end)
tablea a join tableb b on a.id=b.id group by a.id
Sample Data
IF OBJECT_ID('tempdb..#TempTab')IS NOT NULL
DROP TABLE #TempTab
;WITH CTE (ID,CLUB)
AS
(
SELECT 1 , 2 UNION ALL
SELECT 1 , 3 UNION ALL
SELECT 1 , 4 UNION ALL
SELECT 2 , 2 UNION ALL
SELECT 2 , 1 UNION ALL
SELECT 3 , 5
)
SELECT ID,
CLUB,
'CLUB'+CAST(ROW_NUMBER()OVER(PARTITION BY ID ORDER BY ID) AS VARCHAR) AS CLUBData
INTO #TempTab
FROM CTE
Dynamic sql
DECLARE #Column nvarchar(1000),#Column2 nvarchar(max),
#Sql nvarchar(max)
SELECT #Column =STUFF((SELECT DISTINCT ', '+QUOTENAME(CLUBData)
FROM #TempTab FOR XML PATH ('')),1,1,'')
SET #Sql = 'SELECT Id,'+#Column +'
FROM
(
SELECT * FROM #TempTab
) AS SRc
PIVOT
(
MAX(CLUB) FOR CLUBData IN ('+#Column+')
) AS pvt
'
PRINT #Sql
EXEC (#Sql)
Result
Id CLUB1 CLUB2 CLUB3
-------------------------
1 3 4 2
2 1 2 NULL
3 5 NULL NULL

Multiple rows show in a single row using query in sql?

I want to display the department no. and the number of employees in each department from EMP table in a single row. I had one query which display the result in separate rows.
select deptno, count(*) from emp
group by deptno;
Dptno Count(*)
10 5
20 3
30 4
I want to display the result as a single-row. For example:
Dpt10 Count(*) Dpt20 Count(*) Dpt30 Count(*)
10 5 20 3 30 4
The output in this forum is not proper but try to understand that the no. 5,3 & 4 should be below count(*) column and 10,20 & 30 should be below deptno.
Since pivot doesn't support several aggregates in SQL Server:
with t as (
select 10 id, 15 su union all
select 10 id, 10 su union all
select 10 id, 5 su union all
select 20 id, 135 su union all
select 20 id, 100 su union all
select 20 id, 15 su union all
select 30 id, 150 su union all
select 30 id, 1000 su union all
select 30 id, 500 su
)
select max(case when id = 10 then id end) dept10
, count(case when id = 10 then id end) dept10_cnt
, max(case when id = 20 then id end) dept20
, count(case when id = 20 then id end) dept20_cnt
, max(case when id = 30 then id end) dept30
, count(case when id = 30 then id end) dept30_cnt
from t
SQLFiddle
In SQL Server, there are several ways that you can convert multiple rows of data into columns.
If you needed to just convert the count of each deptno into columns, then you could do this easily with either the PIVOT function or a CASE/aggregate combination
select
sum(case when deptno = 10 then 1 else 0 end) Count_Dpt10,
sum(case when deptno = 20 then 1 else 0 end) Count_Dpt20,
sum(case when deptno = 30 then 1 else 0 end) DCount_pt30
from emp
See Demo
But part of the problem is that you want to pivot both the DeptNo and the Total_Count into column - this would need to use 2 different aggregate functions. In your situation the PIVOT function won't work, so you'd have to use a different aggregate function along with a CASE expression similar to:
select
max(case when deptno = 10 then deptno end) Dpt10,
sum(case when deptno = 10 then 1 else 0 end) Count_Dpt10,
max(case when deptno = 20 then deptno end) Dpt20,
sum(case when deptno = 20 then 1 else 0 end) Count_Dpt20,
max(case when deptno = 30 then deptno end) Dpt30,
sum(case when deptno = 30 then 1 else 0 end) DCount_pt30
from emp;
See SQL Fiddle with Demo. Now since you have unknown departments, so you'll need use dynamic sql. This will create a sql string that will then be executed. To create the sql string you'll need to use STUFF and FOR XML PATH. The dynamic code would be:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols
= STUFF((SELECT
', max(case when deptno = '+cast(deptno as varchar(10))+' then deptno end) as '+ QUOTENAME('Dpt'+cast(deptno as varchar(10)))
+ ', sum(case when deptno = '+cast(deptno as varchar(10))+' then 1 else 0 end) as '+ QUOTENAME('Count_Dpt'+cast(deptno as varchar(10)))
from emp
group by deptno
order by deptno
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'SELECT ' + #cols + '
from emp'
exec sp_executesql #query;
See SQL Fiddle with Demo. this gives you a result:
| DPT10 | COUNT_DPT10 | DPT20 | COUNT_DPT20 | DPT30 | COUNT_DPT30 |
|-------|-------------|-------|-------------|-------|-------------|
| 10 | 5 | 20 | 3 | 30 | 4 |
You can try this -
Schema
DECLARE #emp TABLE ([deptno] int NULL, [deptcount] int NULL);
INSERT #emp ([deptno], [deptcount]) VALUES (10, 5), (20, 3), (30, 4);
Query
SELECT STUFF((
SELECT ' ' + CAST([deptno] AS VARCHAR) + ' ' + CAST([deptcount] AS VARCHAR)
FROM #emp
FOR XML PATH('')
), 1, 1, '')
OutPut
10 5 20 3 30 4

SQL Server Rows to Multi-Columns

I have the following table and data:
CREATE TABLE SourceTbl ([Code] varchar(3), [Total] decimal, [Date] datetime );
INSERT INTO SourceTbl ([Code], [Total], [Date])
VALUES ('AA', 100, '2012-12-01'), ('AA', 200, '2013-02-01'), ('BB', 50, '2012-01-01');
A simple select will return
Code | Total | Date
'AA' | 100 | 2012-12-01
'AA' | 200 | 2013-02-01
'BB' | 50 | 2012-01-01
but what I need is the following
Code | Total | Date | Total | Date
'AA | 200 | 2013-02-01 | 100 | 2012-12-01
'BB | 50 | 2012-01-01 | null | null
I have been trying to do this using a PIVOT operator but without success (based on the question SQL Server Pivot multiple columns based on one column).
Using that example, all I get are two rows with null values.
The Total/Date columns can be repeated 13 times and they must be ordered by Date DESC.
SQL Fiddle: http://sqlfiddle.com/#!3/f37a1/2
Any help is appreciated!
Thanks!
If you need just two columns:
with cte as (
select *, row_number() over(partition by Code order by Date) as rn
from SourceTbl
)
select
code,
max(case when rn = 1 then Total end) as Total1,
max(case when rn = 1 then Date end) as Date1,
max(case when rn = 2 then Total end) as Total2,
max(case when rn = 2 then Date end) as Date2
from cte
group by code
=> sql fiddle demo
dynamic solution:
declare #stmt nvarchar(max)
;with cte as (
select distinct
cast(row_number() over(partition by Code order by Date) as nvarchar(max)) as rn
from SourceTbl
)
select #stmt = isnull(#stmt + ', ', '') +
'max(case when rn = ' + rn + ' then Total end) as Total' + rn + ',' +
'max(case when rn = ' + rn + ' then Date end) as Date' + rn
from cte
order by rn
select #stmt = '
with cte as (
select *, row_number() over(partition by Code order by Date) as rn
from SourceTbl
)
select
code, ' + #stmt + ' from cte group by code'
exec sp_executesql
#stmt = #stmt
=> sql fiddle demo
Are you trying to dynamically create columns in your result set?
If you had a third record of 'AA' with a total of 300 and the date of 03/01/2013 would you that mean you would want something like this displayed?
Code | Total | Date | Total | Date | Total | Date
AA | 200 | 2013-02-01 | 100 | 2012-12-01| 300 | 03-01-13
BB | 50 | 2012-01-01 | null | null | null | null

MS SQL - One to Many Relationship - Need to return single row

I have the following tables -
Search Result
----------------
SearchResultID PK
ProductID FK
SearchQuery
WebsiteName
URL
IsFound
CreatedOn
BatchID
Name
SearchResultItem
-----------------
SearchResultItemID PK
SearchResultID FK
Name
Value
These tables have a one to many relationship, so one Search Result, can have many Search Result Items.
I can do an INNER JOIN on these tables however that obviously gives one row per each Search Result Item. Ideally I would like one row per Search Result, for example...
SearchResultID | ProductID | SearchQuery | WebsiteName | URL | IsFound |
CreatedOn | BatchID | Name | SearchResultItemID | Name 1 | Value 1 | Name 2 |
Value 2 | Name 3 | Value 3 |
Is this possible to do? And if so, can someone point me in the right direction as to how I would do this - I think it would be something like this, only in ms-sql - one to many sql select into single row - mysql
You can use the ROW_NUMBER() function to give each search result item a rank within each search result:
SELECT SearchResultItemID,
SearchResultID,
Name,
Value,
RowNumber = ROW_NUMBER() OVER(PARTITION BY SearchResultID ORDER BY SearchresultItemID)
FROM SearchResultItem;
If you have a know number of items then you can use aggregate functions to get each name/value pair:
WITH RankedItem AS
( SELECT SearchResultItemID,
SearchResultID,
Name,
Value,
RowNumber = ROW_NUMBER() OVER(PARTITION BY SearchResultID ORDER BY SearchresultItemID)
FROM SearchResultItem
)
SELECT SearchResultID,
Name1 = MIN(CASE WHEN RowNumber = 1 THEN Name END),
Value1 = MIN(CASE WHEN RowNumber = 1 then Value END),
Name2 = MIN(CASE WHEN RowNumber = 2 THEN Name END),
Value2 = MIN(CASE WHEN RowNumber = 2 then Value END),
Name3 = MIN(CASE WHEN RowNumber = 3 THEN Name END),
Value3 = MIN(CASE WHEN RowNumber = 3 then Value END),
Name4 = MIN(CASE WHEN RowNumber = 4 THEN Name END),
Value5 = MIN(CASE WHEN RowNumber = 4 then Value END)
FROM RankedItem
GROUP BY SearchResultID;
You can then join this back to your Search result table giving a full query:
WITH RankedItem AS
( SELECT SearchResultItemID,
SearchResultID,
Name,
Value,
RowNumber = ROW_NUMBER() OVER(PARTITION BY SearchResultID ORDER BY SearchresultItemID)
FROM SearchResultItem
), Items AS
( SELECT SearchResultID,
Name1 = MIN(CASE WHEN RowNumber = 1 THEN Name END),
Value1 = MIN(CASE WHEN RowNumber = 1 then Value END),
Name2 = MIN(CASE WHEN RowNumber = 2 THEN Name END),
Value2 = MIN(CASE WHEN RowNumber = 2 then Value END),
Name3 = MIN(CASE WHEN RowNumber = 3 THEN Name END),
Value3 = MIN(CASE WHEN RowNumber = 3 then Value END),
Name4 = MIN(CASE WHEN RowNumber = 4 THEN Name END),
Value4 = MIN(CASE WHEN RowNumber = 4 then Value END)
FROM RankedItem
GROUP BY SearchResultID
)
SELECT SearchResult.SearchResultID,
SearchResult.ProductID,
SearchResult.SearchQuery,
SearchResult.WebsiteName,
SearchResult.URL,
SearchResult.IsFound,
SearchResult.CreatedOn,
SearchResult.BatchID,
SearchResult.Name,
Items.Name1,
Items.Value1,
Items.Name2,
Items.Value2,
Items.Name3,
Items.Value3,
Items.Name4,
Items.Value4
FROM SearchResult
INNER JOIN Items
ON SearchResult.SearchResultID = Items.SearchResultID;
Example on SQL Fiddle
If you want to return a variable number of values then you will need to use dynamic SQL:
DECLARE #SQL NVARCHAR(MAX) = '';
SELECT #SQL = #SQL + ',[Name' + rn + '], [Value' + rn + '] '
FROM ( SELECT DISTINCT
rn = CAST(ROW_NUMBER() OVER(PARTITION BY SearchResultID ORDER BY SearchresultItemID) AS VARCHAR)
FROM SearchResultItem
) p;
SET #SQL = 'WITH RankedItem AS
( SELECT SearchResultItemID,
SearchResultID,
Name,
Value,
RowNumber = ROW_NUMBER() OVER(PARTITION BY SearchResultID ORDER BY SearchresultItemID)
FROM SearchResultItem
), UnPivoted AS
( SELECT upvt.SearchResultID,
Name = upvt.n + CAST(RowNumber AS VARCHAR),
upvt.v
FROM RankedItem
UNPIVOT
( n
FOR v IN ([Name], [Value])
) upvt
), Pivoted AS
( SELECT *
FROM UnPivoted
PIVOT
( MAX(V)
FOR Name IN (' + STUFF(#SQL, 1, 1, '') + ')
) pvt
)
SELECT SearchResult.SearchResultID,
SearchResult.ProductID,
SearchResult.SearchQuery,
SearchResult.WebsiteName,
SearchResult.URL,
SearchResult.IsFound,
SearchResult.CreatedOn,
SearchResult.BatchID,
SearchResult.Name' + #SQL + '
FROM SearchResult
INNER JOIN Pivoted
ON SearchResult.SearchResultID = Pivoted.SearchResultID;';
EXECUTE SP_EXECUTESQL #SQL;
Example on SQL Fiddle
N.B. I have intentionally used a different way of doing this in dynamic sql just to show there is more than one way to achieve the result of combining the rows.

Select return dynamic columns

I have two tables: Standards and Service Offerings. A Standard can have multiple Service Offerings. Each Standard can have a different number of Service Offerings associated to it.
What I need to be able to do is write a view that will return some common data and then list the service offerings on one line. For example:
Standard Id | Description | SO #1 | SO #2 | SO #3 | ... | SO #21 | SO Count
1 | One | A | B | C | ... | G | 21
2 | Two | A | | | ... | | 1
3 | Three | B | D | E | ... | | 3
I have no idea how to write this. The number of SO columns is set to a specific number (21 in this case), so we cannot exceed past that.
Any ideas on how to approach this?
A place I started is below. It just returned multiple rows for each Service Offering, when they need to be on one row.
SELECT *
FROM SERVICE_OFFERINGS
WHERE STANDARD_KEY IN (SELECT STANDARD_KEY
FROM STANDARDS)
Additional SQL
So here is the SQL I have that returns everything that I want, but will return 11 rows due to there being 11 Service Offerings. I have been trying the pivot table and can't seem to figure it out with this. Can someone help with a code example?
SELECT DISTINCT stpc.standard_key,
stpc.test_id,
NULL AS pricebook_id,
stpc.stabdard_name AS description,
stpc.date_start AS begin_date,
stpc.date_end AS end_date,
sopd.service_offering_id
FROM STANDARDS stpc,
SERVICE_OFFERINGS sopd
WHERE 1=1
AND sopd.standard_key = stpc.standard_key
ORDER BY stpc.standard_key, sopd.service_offering_id
UPDATE
Since the database does not suppose PIVOT tables (and couldn't figure out the XML suggestion), I had to do a little tricky SQL to get it to work. Here is what I used:
select stpc.oracle_product_code AS test_id,
CASE WHEN stpc.store_key = 200 THEN 'CE_USAUSD09'
WHEN stpc.store_key = 210 THEN 'CE_CANCAD09' END AS pricebook_id,
stpc.standard_name AS its_test_desc,
CONVERT(VARCHAR(10), stpc.date_start, 101) AS begin_date,
CONVERT(VARCHAR(10), stpc.date_end, 101) AS end_date,
MAX(CASE WHEN rn = 1 THEN b.service_offering_id END) AS SERVICE_OFFERING_1,
MAX(CASE WHEN rn = 2 THEN b.service_offering_id END) AS SERVICE_OFFERING_2,
MAX(CASE WHEN rn = 3 THEN b.service_offering_id END) AS SERVICE_OFFERING_3,
MAX(CASE WHEN rn = 4 THEN b.service_offering_id END) AS SERVICE_OFFERING_4,
MAX(CASE WHEN rn = 5 THEN b.service_offering_id END) AS SERVICE_OFFERING_5,
MAX(CASE WHEN rn = 6 THEN b.service_offering_id END) AS SERVICE_OFFERING_6,
MAX(CASE WHEN rn = 7 THEN b.service_offering_id END) AS SERVICE_OFFERING_7,
MAX(CASE WHEN rn = 8 THEN b.service_offering_id END) AS SERVICE_OFFERING_8,
MAX(CASE WHEN rn = 9 THEN b.service_offering_id END) AS SERVICE_OFFERING_9,
MAX(CASE WHEN rn = 10 THEN b.service_offering_id END) AS SERVICE_OFFERING_10,
MAX(CASE WHEN rn = 11 THEN b.service_offering_id END) AS SERVICE_OFFERING_11,
MAX(CASE WHEN rn = 12 THEN b.service_offering_id END) AS SERVICE_OFFERING_12,
MAX(CASE WHEN rn = 13 THEN b.service_offering_id END) AS SERVICE_OFFERING_13,
MAX(CASE WHEN rn = 14 THEN b.service_offering_id END) AS SERVICE_OFFERING_14,
MAX(CASE WHEN rn = 15 THEN b.service_offering_id END) AS SERVICE_OFFERING_15,
MAX(CASE WHEN rn = 16 THEN b.service_offering_id END) AS SERVICE_OFFERING_16,
MAX(CASE WHEN rn = 17 THEN b.service_offering_id END) AS SERVICE_OFFERING_17,
MAX(CASE WHEN rn = 18 THEN b.service_offering_id END) AS SERVICE_OFFERING_18,
MAX(CASE WHEN rn = 19 THEN b.service_offering_id END) AS SERVICE_OFFERING_19,
MAX(CASE WHEN rn = 20 THEN b.service_offering_id END) AS SERVICE_OFFERING_20,
MAX(CASE WHEN rn = 21 THEN b.service_offering_id END) AS SERVICE_OFFERING_21,
MAX(rn) AS service_offering_count
FROM (
select standard_key,
service_offering_id,
row_number() over (partition by standard_key order by standard_key) rn
from SERVICE_OFFERINGS
) B,
SERVICE_OFFERINGS sopd,
STANDARDS stpc
where b.service_offering_id = sopd.service_offering_id
AND b.standard_key = stpc.standard_key
AND sopd.standard_key = stpc.standard_key
AND stpc.store_key IN (200,210)
AND stpc.create_date > '03/29/2010'
group by stpc.oracle_product_code,stpc.store_key,stpc.standard_name,stpc.date_start,stpc.date_end
You can use the PIVOT functionality for this.
Check out http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=PIVOTData
Instead of PIVOT, you should use a combination of FOR XML and SplitToColumns.
Use FOR XML and pivot out your Offerings to a single column Concatenating Row Values in Transact-SQL
Then use a CTE style function to break down a single cell into columns as shown here http://www.sqlservercentral.com/articles/CTE/67974/
This will give you a table pivotted out in the fashion that you need.
Then do arithmetic to get a count of non-null columns and you have the count you need at the end.
Yep, pivot queries are what you need to use.
Are the 21 column always the same, or is it you can show no more than 21 columns (out of, say, hundreds)? If the actual colmns can vary from query to query, you'll have to look into writing dynamic queries (build the the query as a string--incorporating the columns to be pivoted--and then execute the string).
Philip is right. If you will always have 21 columns, its a simple Pivot query. I paste here a sample code you could use.
But if the number of columns would vary betwenn 1 and 21, you'll have to write a dynamic query.
SELECT standard_key, stabdard_name, [A] as SO1, [B] as SO2, [C] as SO3, [D] as SO4, [E] as SO5....-- and so on with the other columns
FROM
(SELECT ST.standard_key, ST.stabdard_name, SO.service_offering_id
FROM SERVICE_OFFERINGS SO
INNER JOIN STANDARDS ST
ON SO.standard_key= ST.standard_key)p
PIVOT
(
MAX (service_offering_id)
FOR service_offering_id IN
( [A], [B], [C], [D], [E]....-- and so on with the other values)
) AS pvt
ORDER BY standard_key
If the colums may vary yo can try with something like this:
declare #sql nvarchar(max)
declare #sql2 nvarchar(max)
SET #sql2=''
set #sql = '
select
standard_key, stabdard_name,'
select #sql = #sql + '['+ service_offering_id + '] AS [SO' + convert(varchar, Row_number() OVER (ORDER BY service_offering_id))+ '],'
from (select distinct [service_offering_id] from [SERVICE_OFFERINGS]) as moduleids
select #sql2 = #sql2 + '['+ service_offering_id + '],'
from (select distinct [service_offering_id] from [SERVICE_OFFERINGS]) as moduleids
set #sql2 = substring(#sql2,1,len(#sql2)-1)
set #sql = substring(#sql,1,len(#sql)-1) + '
FROM
(SELECT ST.standard_key, ST.stabdard_name, SO.service_offering_id
FROM SERVICE_OFFERINGS SO
INNER JOIN STANDARDS ST
ON SO.standard_key= ST.standard_key)p
PIVOT
(
MAX (service_offering_id)
FOR service_offering_id IN
(' + #sql2 +
')) AS pvt
ORDER BY standard_key'
print #sql
exec sp_executesql #sql