Select return dynamic columns - sql

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

Related

How to combine each three rows into single column in SQL Server 2008?

NOOfDays DISTRInutorID
-------------------------
1 abcd
1 cdef
2 DFSDF
2 SFSDD
2 SDFSD
2 WAOYWAR
7 WEFIWE
7 WEOFYWE
7 WFYREU
The above is one of my sample tables, I want to combine each two rows based on NOOfDays.
Expected output:
NOOfDays DiSTRInutorID
------------------------------
1 abcd, cdef
2 DFSDF, SFSDD
2 SDFSD, WAOYWAR
7 WEFIWE, WEOFYWE
7 WFYREU
In ancient versions of SQL Server, the logic looks like:
select n.NOOfDays,
stuff( (select ',' + t2.DISTRInutorID
from t t2
where t2.NOOfDays = n.NOOfDays
for xml path ('')
), 1, 1, ''
) as list
from (select distinct NOOfDays from t) n;
EDIT:
I misunderstood the original question. This is what you are looking for:
with cte as (
select t.*, row_number() over (order by (select null)) - 1 as seqnum
from t
)
select NOOfDays,
(case when count(*) = 1 then min(DISTRInutorID)
else max(case when seqnum % 2 = 0 then DISTRInutorID end) + ',' + max(case when seqnum % 2 = 1 then DISTRInutorID end)
end) as list
from cte
group by NOOfDays, floor(seqnum / 2);
Note that SQL tables represent unordered sets. This arbitrarily pairs rows where the first column is the same, but there is no guarantee that these are adjacent -- for the simple reason that "adjacent" is not defined.
Here is a db<>fiddle.

split columns (more than one) into multiple columns with dynamic sql [duplicate]

This question already has answers here:
SQL Server dynamic PIVOT query?
(9 answers)
Closed 4 years ago.
I have table with data as below
I have got result to convert one column to multiple columns. But I need output to convert multiple columns
The result is expected as below
Output needed as
Name Q1 G1 Q2 G2 Q3 G3
Antony HSE A Degree C NULL NULL
Bob HSE B Degree B Masters A
Marc HSE D Degree C Masters B
If those Qualifications have fixed values, then you can get that result via conditional aggregation.
SELECT
Name,
MAX(CASE WHEN Qualification = 'HSE' THEN Qualification END) AS Q1,
MAX(CASE WHEN Qualification = 'HSE' THEN Grade END) AS G1,
MAX(CASE WHEN Qualification = 'Degree' THEN Qualification END) AS Q2,
MAX(CASE WHEN Qualification = 'Degree' THEN Grade END) AS G2,
MAX(CASE WHEN Qualification = 'Masters' THEN Qualification END) AS Q3,
MAX(CASE WHEN Qualification = 'Masters' THEN Grade END) AS G3
FROM YourTable
GROUP BY Name
ORDER BY Name
If the qualification names aren't fixed, then you could generate a row_number and use that.
Then you can add as many Qn & Gn as a Name can have qualifications.
To test that: select top 1 [Name], count(*) Total from #YourTable group by [Name] order by Total desc
SELECT
Name,
MAX(CASE WHEN RN = 1 THEN Qualification END) AS Q1,
MAX(CASE WHEN RN = 1 THEN Grade END) AS G1,
MAX(CASE WHEN RN = 2 THEN Qualification END) AS Q2,
MAX(CASE WHEN RN = 2 THEN Grade END) AS G2,
MAX(CASE WHEN RN = 3 THEN Qualification END) AS Q3,
MAX(CASE WHEN RN = 3 THEN Grade END) AS G3
FROM
(
SELECT Name, Qualification, Grade,
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Qualification) AS RN
FROM YourTable
) q
GROUP BY Name
ORDER BY Name
Or doing it dynamic
declare #MaxTotalQualifications int = (select top 1 count(*) from YourTable group by [Name] order by count(*) desc);
declare #cols varchar(max);
WITH DIGITS(n) AS (
SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n)
)
, NUMBERS(n) AS
(
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM DIGITS AS ones
CROSS JOIN DIGITS as tens
CROSS JOIN DIGITS as hundreds
CROSS JOIN DIGITS as thousands
)
select #cols = concat(#cols+CHAR(13)+CHAR(10)+', ', 'MAX(CASE WHEN RN = ', n ,' THEN Qualification END) AS [Q', n ,'], MAX(CASE WHEN RN = ', n ,' THEN Grade END) AS [G', n,']')
from NUMBERS
WHERE n BETWEEN 1 AND #MaxTotalQualifications;
-- select #MaxTotalQualifications as MaxTotalQualifications, #cols as cols;
declare #DynSql nvarchar(max);
set #DynSql = N'SELECT Name, '+ #cols + N'
FROM
(
SELECT Name, Qualification, Grade,
ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Qualification) AS RN
FROM YourTable
) q
GROUP BY Name
ORDER BY Name';
-- select #DynSql as DynSql;
exec(#DynSql);
A test on db<>fiddle here

Performing additions within multiple columns of different rows in a SQL Server table based on the text in a column

I am trying to figure a query which performs some additions and subtractions of data in different rows and different columns based on the text/data in some other column in the same table.
Problem can be clearly addressed with the following example
Consider, I have table named Outright with four fields/columns with several records as follows
Product Term Bid Offer
------------------------------
A Aug14 P Q
A/B Aug14 R S
B Aug14 X Y
B Sep14 ab xy
B/C Sep14 pq rs
C Sep14 wx yz
When I run the query it should look for the Products that is separated by / in the above case there are two products of that type A/B and B/Cand then it should look for individual products based the those that are separated by / like we have a product A/B which is separated by a /, so it should look for product A and B with same term as A/B and perform some operations and return the data as follows
Product Term Bid Offer
------------------------------
A Aug14 a b
B Aug14 c d
B Sep14 ab cd
C Sep14 abc cde
in the above results
a=R+Y b=S+X
c=Q-S d=P-R
where P,Q,R,S,X,Y are Bid and Offer values from the table Outright
similar calculations are applied for all other data too like for B/C Sep14.. and many other
Example
Table Outright
A Oct14 -175 -75
B Oct14 125 215
A/B Oct14 NULL -150
Result should be
A Oct14 NULL -150+125=-25
B Oct14 -75-(-150)=75 NULL
The above values are calculated using the equations mentioned earlier
May I know a better way to solve it in SQL Server 2012?
Ok lets create some test data:
DECLARE #Outright TABLE
(
Product VARCHAR(10),
Term VARCHAR(10),
Bid VARCHAR(10),
Offer VARCHAR(10)
)
INSERT INTO #Outright
VALUES
('A', 'Aug14','P','Q'),
('A/B','Aug14','R','S'),
('B', 'Aug14','X','Y');
Making a cte to try to figure out the logic posted above and match the single product line to the multiproduct line
;WITH t AS
(
SELECT
a.*,
d.DRN,
d.Bid dBid,
d.Product dProduct,
d.Offer dOffer,
ROW_NUMBER() OVER (ORDER BY a.Product) RN
FROM #Outright a
OUTER APPLY
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY d.Product) DRN
FROM #Outright d
WHERE d.Product LIKE (a.Product + '/%')
OR d.Product LIKE ('%/' + a.Product)
) d
WHERE d.Product IS NOT NULL
)
Now we try to implement the + - rules as stated above (bids to offers, offers to bids, etc)
SELECT
*,
CASE WHEN RN = 1 THEN FE1_1 + '+' + FE1_2 ELSE FE1_1 + '-' + FE1_2 END Col1,
CASE WHEN RN = 1 THEN FE2_1 + '+' + FE2_2 ELSE FE2_1 + '-' + FE2_2 END Col2
FROM
(
SELECT
MAX(CASE WHEN RN = 1 THEN Product END) Prod1,
MAX(CASE WHEN RN = 1 THEN Term END) Term1,
MAX(CASE WHEN RN = 1 THEN dBid END) FE1_1,
MAX(CASE WHEN RN = 2 THEN Offer END) FE1_2,
MAX(CASE WHEN RN = 2 THEN dOffer END) FE2_1,
MAX(CASE WHEN RN = 2 THEN Bid END) FE2_2,
1 RN
FROM t
UNION ALL
SELECT
MAX(CASE WHEN RN = 2 THEN Product END) Prod2,
MAX(CASE WHEN RN = 2 THEN Term END) Term2,
MAX(CASE WHEN RN = 1 THEN Offer END) FE3_1,
MAX(CASE WHEN RN = 2 THEN dOffer END) FE3_2,
MAX(CASE WHEN RN = 1 THEN Bid END) FE4_1,
MAX(CASE WHEN RN = 2 THEN dBid END) FE4_2,
2 RN
FROM t
) d
Here is the output, with some extra columns to show the data being pulled
Prod1 Term1 FE1_1 FE1_2 FE2_1 FE2_2 RN Col1 Col2
A Aug14 R Y S X 1 R+Y S+X
B Aug14 Q S P R 2 Q-S P-R

X Number Of Rows Into One Row Based On One Column

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

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.