Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can try ur problem with <strong>DYNAMIC PIVOTING</strong>.</p> <p>A sample is given here.</p> <p>------------------<strong>Initial Table Creation &amp; Data Population</strong>---------------</p> <pre><code>create table #tblpk (id int identity,groupid int) insert into #tblpk select 1 union all select 1 union all select 1 union all select 2 union all select 2 union all select 1 union all select 3 create table #tblfk (id int, groupdate datetime, flag int) insert into #tblfk select 1,'01/02/2009',1 union all select 1,'02/02/2009',0 union all select 1,'03/02/2009',1 </code></pre> <p>----------- <strong>Program Starts</strong> -------------------------------------------</p> <p>-- Variable Declarations</p> <pre><code>declare @col_list varchar(max) declare @dynquery varchar(max) </code></pre> <p><em>--Step 1: Get all the matching records from the two tables</em></p> <pre><code>select tpk.id id ,tfk.groupdate groupdate ,tfk.flag into #allRectbl from #tblpk tpk inner join #tblfk tfk on tpk.groupid = tfk.id </code></pre> <p><em>--Step 2: Get the unique dynamic columns</em></p> <pre><code>select distinct(Cols) as DynamicCols into #dynamicColumns from ( select IsNull(@col_list,'') + '[' + cast(groupdate as varchar(32)) + '],' as Cols from #allRectbl )X(Cols) </code></pre> <p><em>--Step 3: Make the dynamic pivot columns</em></p> <pre><code>select @col_list = IsNull(@col_list,'') + DynCols from ( select left(DynCols,len(DynCols)-1) DynCols from ( select cast(DynamicCols as varchar(max)) from #dynamicColumns for xml path ('') ) X(DynCols) )Y(DynCols) </code></pre> <p>-<em>-Step 4: Make the Pivoting happen</em></p> <pre><code>set @dynquery = 'select * ' + 'from #allRectbl ' + 'pivot ( ' + 'max(flag) ' + 'for groupdate ' + 'in (' + @col_list + ') ' + ') as pvt' </code></pre> <p>--<em>Step 5: Execute the query</em></p> <pre><code>exec (@dynquery) </code></pre> <p>-<em>-Step 6: Droping the test tables</em> -------------------------</p> <pre><code>drop table #tblpk drop table #tblfk drop table #allRectbl drop table #dynamicColumns </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload