Data is in given format-
Id Date Location
a123 6/6/2016 mmp
a123 6/7/2016 jpr
a123 6/8/2016 hjl
a123 6/9/2016 jhag
a678 6/10/2016 hjlwe
a678 6/11/2016 mkass
a980 6/7/2016 asdadf
a980 6/7/2016 lasdj
a980 6/7/2016 xswd
I want the same in given format-:
Id Date 1 Location1 Date 2 Location 2 Date 3 Location 3
a123 6/6/2016 mmp 6/7/2016 jpr 6/8/2016 hjl
a678 6/10/2016 hjlwe 6/11/2016 mkass
a980 6/7/2016 asdadf 6/7/2016 lasdj 6/7/2016
How to do that in SQL?
You can use ROW_NUMBER() with conditional aggregation :
SELECT s.id,
MAX(CASE WHEN s.rnk = 1 THEN s.date END) as date_1,
MAX(CASE WHEN s.rnk = 1 THEN s.location END) as location_1,
MAX(CASE WHEN s.rnk = 2 THEN s.date END) as date_2,
MAX(CASE WHEN s.rnk = 2 THEN s.location END) as location_2,
MAX(CASE WHEN s.rnk = 3 THEN s.date END) as date_3,
MAX(CASE WHEN s.rnk = 3 THEN s.location END) as location_3
FROM(
SELECT t.*,
ROW_NUMBER() OVER(PARTITION BY t.id ORDER BY t.Date) as rnk
FROM YourTable t) s
GROUP BY s.id
This can also be solved with PIVOT but I prefer to use conditional aggregation as long as the amount of the columns is limited .
If you need to add more levels, just follow the logic and replace 3 with 4 and so on..
Also you can make it with PIVOT (if number of columns can change dynamically you must use dynamic SQL):
;WITH cte AS (
SELECT *
FROM (VALUES
('a123', '6/6/2016', 'mmp'),
('a123', '6/7/2016', 'jpr'),
('a123', '6/8/2016', 'hjl'),
('a123', '6/9/2016', 'jhag'),
('a678', '6/10/2016', 'hjlwe'),
('a678', '6/11/2016', 'mkass'),
('a980', '6/7/2016', 'asdadf'),
('a980', '6/7/2016', 'lasdj'),
('a980', '6/7/2016', 'xswd')
) as t(Id, [Date], [Location])
)
SELECT p1.Id,
p1.[Date1],
p2.[Location1],
p1.[Date2],
p2.[Location2],
p1.[Date3],
p2.[Location3],
p1.[Date4],
p2.[Location4]
FROM
(SELECT *
FROM (
SELECT Id,
[Date],
'Date' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)) as rn
fROM cte
) AS D
PIVOT (
MAX([Date]) for RN in ([Date1],[Date2],[Date3],[Date4])
) as pvt
) as p1
LEFT JOIN
(SELECT *
FROM (
SELECT Id,
[Location],
'Location' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)) as rn
fROM cte
) AS D
PIVOT (
MAX([Location]) for RN in ([Location1],[Location2],[Location3],[Location4])
) as pvt
) as p2
ON p1.Id = p2.Id
Output:
Id Date1 Location1 Date2 Location2 Date3 Location3 Date4 Location4
---- --------- --------- --------- --------- --------- --------- --------- ---------
a123 6/6/2016 mmp 6/7/2016 jpr 6/8/2016 hjl 6/9/2016 jhag
a678 6/10/2016 hjlwe 6/11/2016 mkass NULL NULL NULL NULL
a980 6/7/2016 lasdj 6/7/2016 xswd 6/7/2016 asdadf NULL NULL
EDIT
With dynamic SQL (same output):
CREATE TABLE #temp (
Id nvarchar(10),
[Date] date,
[Location] nvarchar(10)
)
INSERT INTO #temp VALUES
('a123', '6/6/2016', 'mmp'),
('a123', '6/7/2016', 'jpr'),
('a123', '6/8/2016', 'hjl'),
('a123', '6/9/2016', 'jhag'),
('a678', '6/10/2016', 'hjlwe'),
('a678', '6/11/2016', 'mkass'),
('a980', '6/7/2016', 'asdadf'),
('a980', '6/7/2016', 'lasdj'),
('a980', '6/7/2016', 'xswd')
DECLARE #locs nvarchar(max),
#dates nvarchar(max),
#cols nvarchar(max),
#sql nvarchar(max)
SELECT #locs = STUFF((
SELECT DISTINCT ',' + QUOTENAME('Location' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)))
FROM #temp
FOR XML PATH('')
),1,1,'')
SELECT #dates = STUFF((
SELECT DISTINCT ',' + QUOTENAME('Date' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)))
FROM #temp
FOR XML PATH('')
),1,1,'')
SELECT #cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME('Date' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10))) +
',' + QUOTENAME('Location' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)))
FROM #temp
FOR XML PATH('')
),1,1,'')
SELECT #sql ='
SELECT p1.Id,
'+#cols+'
FROM
(SELECT *
FROM (
SELECT Id,
[Date],
''Date'' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)) as rn
fROM #temp
) AS D
PIVOT (
MAX([Date]) for RN in ('+#dates+')
) as pvt
) as p1
LEFT JOIN
(SELECT *
FROM (
SELECT Id,
[Location],
''Location'' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date]) AS NVARCHAR(10)) as rn
fROM #temp
) AS D
PIVOT (
MAX([Location]) for RN in ('+#locs+')
) as pvt
) as p2
ON p1.Id = p2.Id'
EXECUTE sp_executesql #sql
DROP TABLE #temp
If you don't know how many columns you have, you can use a dynamic version of sagi's answer. Here is one using a dynamic crosstab:
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql =
'SELECT
t.id' + CHAR(10);
SELECT #sql = #sql +
(SELECT
' , MAX(CASE WHEN rn = ' + CAST(rn AS VARCHAR(10)) + ' THEN t.Date END) AS ' + QUOTENAME('Date' + CAST(rn AS VARCHAR(10))) + CHAR(10) +
' , MAX(CASE WHEN rn = ' + CAST(rn AS VARCHAR(10)) + ' THEN t.Location END) AS ' + QUOTENAME('Location' + CAST(rn AS VARCHAR(10))) + CHAR(10)
FROM (
SELECT DISTINCT
ROW_NUMBER() OVER (PARTITION BY Id ORDER BY(SELECT NULL)) AS rn
FROM tbl
) t
ORDER BY rn
FOR XML PATH(''));
SELECT #sql = #sql +
'FROM (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Date) AS rn
FROM tbl
) t
GROUP BY t.Id;';
PRINT (#sql);
EXEC (#sql);
ONLINE DEMO
Related
Source:
ItemId
ItemName
Nutrient
GAV
A
Beef
Vit A
1
A
Beef
Vit B
2
A
Beef
Vit C
3
target:
Id
Name
Nut1
GAV1
Nut2
GAV2
Nut3
GAV3
A
Beef
VitA
1
VitB
2
VitC
3
How can we achieve this with ms-sql query?
Assuming GAV is NOT sequential as presented, we'll have to use the window function row_number() and some Dynamic SQL
Example or dbFiddle
Declare #SQL varchar(max)
Select #SQL = string_agg( concat('[',ColName,ColNr,']','=','max(case when ColNr =',ColNr,' then ',ColName,' end)') , ',') within group (ORDER BY ColNr,ColName Desc)
From (values ('Nutrient'),('GAV') ) A(ColName)
Cross Join ( Select Distinct ColNr = row_number() over( partition by ItemID order by GAV) from YourTable ) B
Set #SQL = '
Select ItemID
,ItemName
,' + #SQL + '
From ( Select *
,ColNr = row_number() over( partition by ItemID order by GAV )
From YourTable
) A
Group By ItemID
,ItemName
'
Exec(#SQL)
Results
UPDATE 2016 Version
Declare #SQL varchar(max) = ''
Select #SQL = #SQL + concat(',','[',ColName,ColNr,']','=','max(case when ColNr =',ColNr,' then ',ColName,' end)')
From (values ('Nutrient'),('GAV') ) A(ColName)
Cross Join ( Select Distinct ColNr = row_number() over( partition by ItemID order by GAV) from YourTable ) B
Order By ColNr,ColName Desc
Set #SQL = '
Select ItemID
,ItemName
' + #SQL + '
From ( Select *
,ColNr = row_number() over( partition by ItemID order by GAV )
From YourTable
) A
Group By ItemID
,ItemName
'
Exec(#SQL)
We need to list all numbers as a flat data set, how can we do that?
Table Name: Telephone
ID TYPE NUMBER
==================================
123 MN 042153939
123 HN 2242116
123 MN 1234567890
123 HN 12345678
Create Table Telephone
(
ID Integer,
Type char(3),
Number Varchar(20)
);
insert into Telephone values
(123, 'MN', '042153939'),
(123, 'HN', '2242116'),
(123, 'MN', '1234567890'),
(123, 'HN', '12345678');
I want SQL to return data in this format
ID MN#1 Mn#2 HN#1 HN#2
================================================
123 042153939 1234567890 2242116 12345678
Dynamic approach
Init
DROP TABLE IF EXISTS #Telephone;
CREATE TABLE #Telephone(ID INT,Type CHAR(3),Number VARCHAR(20));
INSERT INTO #Telephone (ID,Type,Number) VALUES
(123, 'MN', '042153939'),
(123, 'HN', '2242116'),
(123, 'MN', '1234567890'),
(123, 'HN', '12345678');
The code
DECLARE #ColumnList NVARCHAR(MAX);
SELECT #ColumnList = STUFF((SELECT ',[' + RTRIM(t.[Type]) + '#'
+ CONVERT(NVARCHAR(255),ROW_NUMBER()OVER(PARTITION BY t.[Type] ORDER BY t.ID)) + ']'
FROM #Telephone t FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
;
DECLARE #sql NVARCHAR(MAX) = '';
SET #sql = N'
SELECT ID,' + #ColumnList + N'
FROM (
SELECT t.ID,t.Number, RTRIM(t.[Type]) + ''#'' + CONVERT(NVARCHAR(255),ROW_NUMBER()OVER(PARTITION BY t.[Type] ORDER BY t.ID)) AS [Type]
FROM #Telephone t
) a
PIVOT(MAX(a.Number) FOR a.Type IN (' + #ColumnList + N')) p
'
;
--PRINT #sql
IF #sql IS NOT NULL EXEC(#sql);
try pivoting like below :
SELECT first_column AS <first_column_alias>,
[pivot_value1], [pivot_value2], ... [pivot_value_n]
FROM
(<source_table>) AS <source_table_alias>
PIVOT
(
aggregate_function(<aggregate_column>)
FOR <pivot_column> IN ([pivot_value1], [pivot_value2], ... [pivot_value_n])
) AS <pivot_table_alias>;
We can try using a pivot query with the help of ROW_NUMBER():
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY TYPE DESC, NUMBER) rn
FROM Telephone
)
SELECT
ID,
MAX(CASE WHEN rn = 1 THEN NUMBER END) AS [MN#1],
MAX(CASE WHEN rn = 2 THEN NUMBER END) AS [MN#2],
MAX(CASE WHEN rn = 3 THEN NUMBER END) AS [HN#3],
MAX(CASE WHEN rn = 4 THEN NUMBER END) AS [HN#4]
FROM cte
GROUP BY ID;
You may try this. with row_number() and pivot.
For more info about pivot you may find this link PIVOT.
; with cte as (
select row_number() over (partition by type order by id ) as Slno, * from Telephone
)
, ct as (
select id, type + '#' + cast(slno as varchar(5)) as Type, values from cte
)
select * from (
select * from ct
) as d
pivot
( max(values) for type in ( [MN#1],[Mn#2],[HN#1],[HN#2] )
) as p
This question already has answers here:
SQL Server Pivot Table with multiple column aggregates
(3 answers)
Closed 3 years ago.
Hi I have sample data
Declare #table table
(Name Varchar(10),
Cnt INT,
Vol INT,
Descc VARCHAR(10))
INSERT INTO #table(Name,cnt,vol,Descc)values ('Mohan',21,8,'Fed')
INSERT INTO #table(Name,cnt,vol,Descc)values ('Mohan',1,391,'Fed:::')
Data :
Name Cnt Vol Descc
Mohan 21 8 Fed
Mohan 1 391 Fed:::
How can I get output like this
Name Cnt1 Vol1 Descc1 cnt2 vol2 Descc2
Mohan 21 8 Fed 1 391 Fed::
script I have followed :
Select [1],[2] from (
select NAme,Cnt,vol,DESCc,ROW_NUMBER()OVER(PARTITION BY ID ORDER BY (SELECT NULL))P,'P'+CAST(ROW_NUMBER()OVER(PARTITION BY ID ORDER BY (SELECT NULL))AS VARCHAR)PP from #table )T
PIVOT (MAX(ID) FOR P IN ([1],[2])) AS P
PIVOT (MAX(ID) FOR PP IN ([P1],[P2])) AS P
You can do conditional aggregation :
select Name, max(case when seq = 1 then Cnt end) as cnt1,
max(case when seq = 1 then Vol end) as Vol1,
max(case when seq = 1 then Descc end) as Descc1,
max(case when seq = 2 then Cnt end) as cnt2,
max(case when seq = 2 then Vol end) as Vol2,
max(case when seq = 2 then Descc end) as Descc2
from (select t.*, row_number() over (partition by name order by (select 1 )) as seq
from #table t
) t
group by Name;
Here is a db<>fiddle.
By Dynamic sql
IF OBJECT_ID('tempdb..#TEMP') IS NOT NULL
DROP TABLE #TEMP
DECLARE #table table
(
Name Varchar(10),
Cnt INT,
Vol INT,
Descc VARCHAR(10)
)
INSERT INTO #table(Name,cnt,vol,Descc)values ('Mohan',21,8,'Fed')
INSERT INTO #table(Name,cnt,vol,Descc)values ('Mohan',1,391,'Fed')
;WITH CTE
AS
(
SELECT
ROW_NUMBER()OVER(ORDER BY Name) AS Id,*
FROM #table i
)
SELECT ROW_NUMBER()OVER(ORDER BY (SELECT NULL)) AS Seq,
id,
Name,
Data1,
Data2
+CAST(id AS VARCHAR(10)) AS ReqCol
INTO #TEMP
FROM CTE
CROSS APPLY (VALUES ( CAST(CNT AS varchar(10)),'CNT'),
(CAST(Vol AS varchar(10)),'vol'),
(Descc,'Descc')
)AS Dt (Data1,Data2)
SET NOCOUNT ON
DECLARE #Sql nvarchar(max),
#DynamicColumn nvarchar(max),
#MaxDynamicColumn nvarchar(max)
SELECT #DynamicColumn = STUFF((SELECT ', '+QUOTENAME(CAST(ReqCol AS VARCHAR(10)))
FROM #TEMP ORDER BY Seq FOR XML PATH ('')),1,1,'')
SELECT #MaxDynamicColumn = STUFF((SELECT ', '+'MAX('+QUOTENAME(CAST(ReqCol AS VARCHAR(10)))+') AS '+QUOTENAME(CAST(ReqCol AS VARCHAR(10)))
FROM #TEMP ORDER BY Seq FOR XML PATH ('')),1,1,'')
SET #Sql='SELECT Name,'+ #MaxDynamicColumn+'
FROM
(
SELECT * FROM #TEMP
)AS src
PIVOT
(
MAX(Data1) FOR [ReqCol] IN ('+#DynamicColumn+')
) AS Pvt
GROUP BY Name '
EXEC (#Sql)
PRINT #Sql
SET NOCOUNT OFF
Result
Name CNT1 vol1 Descc1 CNT2 vol2 Descc2
---------------------------------------------------------
Mohan 21 8 Fed 1 391 Fed
My pricelist table looks like this:
ItemCode VendorCode UnitCost StartingDate
333 362 2.31 2016-08-19 00:00:00.0
333 362 2.16 2018-02-22 00:00:00.0
444 362 12.96 2014-01-09 00:00:00.0
444 362 13.10 2015-01-09 00:00:00.0
444 430 13.05 2017-04-01 00:00:00.0
444 550 13.30 2018-02-01 00:00:00.0
I would like to have query result following:
333:(362,2.16,2018-02-22)
444:(362,13.10,2015-01-09),(430,13.05,2017-04-01),(550,13.30,2018-02-01)
So all different Vendors and their prices should be listed and only latest by date.
I got this far:
SELECT
Pricelist.ItemCode + ': '+ temp.data
FROM Pricelist
INNER JOIN (SELECT p1.ItemCode,
STUFF((SELECT '; ' + p2.VendorCode
FROM Pricelist p2
WHERE p2.ItemCode = p1.ItemCode
ORDER BY VendorCode
FOR XML PATH('')), 1, 1, '') AS data
FROM Pricelist p1) as temp
ON Pricelist.ItemCode = temp.ItemCode
GROUP BY Pricelist.ItemCode, temp.data
ORDER BY 1
But not even close to the result I need.
I would use row_number() function :
select concat(itemcode, ':',
stuff( ( select top (1) with ties ',(' +concat(VendorCode, ',', UnitCost ,',', cast(StartingDate as date)) +')'
from Pricelist
where itemcode = p.itemcode
order by row_number() over (partition by VendorCode order by StartingDate desc)
for xml path('')
), 1, 1, ''
))
from Pricelist p
group by itemcode;
Try with this query:
create table #t (ItemCode int, VendorCode int, UnitCost decimal (10,2), StartingDate datetime)
insert into #t values
(333,362, 2.31,'2016-08-19 00:00:00.0'),
(333,362, 2.16,'2018-02-22 00:00:00.0'),
(444,362,12.96,'2014-01-09 00:00:00.0'),
(444,362,13.10,'2015-01-09 00:00:00.0'),
(444,430,13.05,'2017-04-01 00:00:00.0'),
(444,550,13.30,'2018-02-01 00:00:00.0')
;with tr1 as (
select
convert(varchar(100),ItemCode) + ':' as ItemCode,
'(' + convert(varchar(100),VendorCode) + ',' + convert(varchar(100),UnitCost) + ',' + convert(varchar(19),StartingDate,121) + ')' as Vals,
row_number() over (partition by ItemCode,VendorCode order by StartingDate desc) rn
from #t
)
select distinct ItemCode,
stuff((
select ',' + Vals
from tr1 b
where b.ItemCode=tr1.ItemCode
and rn=1
for xml path ('')
),1,1,'')
from tr1
where rn=1
First grouping the itemcodes, and then linking that to a string with the vendor details might be quite performant.
Linking those itemcodes to an OUTER APPLY with a FOR XML works well.
For example :
declare #Pricelist table (ItemCode int, VendorCode int, UnitCost decimal (10,2), StartingDate datetime)
insert into #Pricelist values
(333,362,02.31,'2016-08-19T00:01:00'),
(333,362,02.16,'2018-02-22T00:02:00'),
(444,362,12.96,'2014-01-09T00:03:00'),
(444,362,13.10,'2015-01-09T00:04:00'),
(444,430,13.05,'2017-04-01T00:05:00'),
(444,550,13.30,'2018-02-01T00:06:00');
select concat(itemcode,':',stuff(x.details,1,1,'')) as ItemVendorDetails
from (select distinct itemcode from #Pricelist) i
outer apply
(
select top 1 with ties
concat(',(',VendorCode,',',UnitCost,',',convert(date,StartingDate),')')
from #Pricelist p
where p.ItemCode = i.ItemCode
order by row_number() over (partition by ItemCode, VendorCode order by StartingDate desc)
for xml path('')
) x(details);
Result:
ItemVendorDetails
------------------------------------------------------------------------
333:(362,2.16,2018-02-22)
444:(362,13.10,2015-01-09),(430,13.05,2017-04-01),(550,13.30,2018-02-01)
The following query works with the sample data provided:
;WITH VendorPerItemCTE AS (
SELECT ItemCode,
VendorCode,
UnitCost,
StartingDate,
ROW_NUMBER() OVER (PARTITION BY ItemCode, VendorCode
ORDER BY StartingDate DESC) AS seq
FROM PriceList
)
SELECT CAST(ItemCode AS VARCHAR(12)) + ':' + STUFF(ItemData , 1, 1, '')
FROM (
SELECT DISTINCT p.ItemCode,
(SELECT ', (' + CAST(VendorCode AS VARCHAR(10)) + ', ' +
CAST(UnitCost AS VARCHAR(10)) + ', ' +
CONVERT(VARCHAR(12), StartingDate, 102 ) +
')'
FROM VendorPerItemCTE AS c
WHERE p.ItemCode = c.ItemCode AND c.seq = 1
FOR XML PATH('')) AS ItemData
FROM PriceList AS p) AS t
Demo here
I have a table that has many InsuranceNo's for unique MemberIDs. If there are more than one InsuranceNo, I want the InsuranceNo's to shift to a column, so in the end there is one line per MemberID, with all the iterations of that ID's InsuranceNo's as a Column.
MemberID InsuranceNo
--------------------------
123456 dser
124571 jklh
123456 abcd
I want it to look like this:
MemberID InsuranceNo1 InsuranceNo2
-----------------------------------------------------
123456 dser abcd
124571 jklh
Thank you!
Yet another option... Just change "YourTable" to your actual table name.
Example
Declare #SQL varchar(max) = '
Select *
From (
Select MemberID
,Item = concat(''InsuranceNo'',row_number() over (Partition By MemberID Order By (Select NULL)))
,Value = InsuranceNo
From YourTable
) A
Pivot (max([Value]) For [Item] in (' + Stuff((Select ','+QuoteName(concat('InsuranceNo',ColNr))
From (Select Distinct ColNr=row_number() over (Partition By MemberID Order By (Select NULL)) from YourTable ) A
For XML Path('')),1,1,'') + ') ) p'
--Print #SQL
Exec(#SQL);
Returns
MemberID InsuranceNo1 InsuranceNo2
123456 dser abcd
124571 jklh NULL
If it helps wrap your head around PIVOT, the SQL Generated looks like this:
Select *
From (
Select MemberID
,Item = concat('InsuranceNo',row_number() over (Partition By MemberID Order By (Select NULL)))
,Value = InsuranceNo
From YourTable
) A
Pivot (max([Value]) For [Item] in ([InsuranceNo1],[InsuranceNo2]) ) p
I prefer a dynamic cross tab to the dynamic pivot. I find the syntax far less obtuse and it is super easy if you need to add additional columns. Here is I would go about tackling this. Of course in your case you don't need a temp table because you have an actual table to use.
if OBJECT_ID('tempdb..#Something') is not null
drop table #Something
create table #Something
(
MemberID int
, InsuranceNo varchar(10)
)
insert #Something values
(123456, 'dser')
, (124571, 'jklh')
, (123456, 'abcd')
declare #StaticPortion nvarchar(2000) =
'with OrderedResults as
(
select *, ROW_NUMBER() over(partition by MemberID order by InsuranceNo) as RowNum
from #Something
)
select MemberID';
declare #DynamicPortion nvarchar(max) = '';
declare #FinalStaticPortion nvarchar(2000) = ' from OrderedResults Group by MemberID order by MemberID';
with E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E2
)
select #DynamicPortion = #DynamicPortion +
', MAX(Case when RowNum = ' + CAST(N as varchar(6)) + ' then InsuranceNo end) as InsuranceNo' + CAST(N as varchar(6)) + CHAR(10)
from cteTally t
where t.N <=
(
select top 1 Count(*)
from #Something
group by MemberID
order by COUNT(*) desc
)
select #StaticPortion + #DynamicPortion + #FinalStaticPortion
declare #SqlToExecute nvarchar(max) = #StaticPortion + #DynamicPortion + #FinalStaticPortion;
exec sp_executesql #SqlToExecute