Welcome to dbFreaks.com!
FAQFAQ    SearchSearch      ProfileProfile    Private MessagesPrivate Messages   Log inLog in

Dynamic SQL

 
Goto page Previous  1, 2, 3
   Database Help (Home) -> General Discussions RSS
Next:  Opening Access database  
Author Message
Plamen Ratchev

External


Since: Aug 20, 2008
Posts: 672



(Msg. 31) Posted: Wed Dec 10, 2008 2:37 pm
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: comp>databases>ms-sqlserver (more info?)

Best would be to add the rank to the select list of the final pivot query:

DECLARE @pivot_query NVARCHAR(2000);
SET @pivot_query =
N'SELECT sort, reg, ' + @pivot_cols +
N',ROW_NUMBER() OVER(ORDER BY sort) AS rn ' +
N',RANK() OVER(ORDER BY sort) AS rk ' +
N'FROM (SELECT sort, reg, ' +
N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME), 6),
6) AS year_month, ' +
N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL(5,
2)) AS perc ' +
N'FROM #temp1) AS F ' +
N'PIVOT ' +
N'(MAX(perc) FOR year_month IN (' + @pivot_cols + ')) AS P ' +
N'ORDER BY sort;';

--
Plamen Ratchev
http://www.SQLStudio.com

 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
JJ297

External


Since: Feb 01, 2008
Posts: 51



(Msg. 32) Posted: Thu Dec 11, 2008 4:54 am
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Dec 10, 2:53 pm, JJ297 wrote:
> On Dec 10, 2:37 pm, Plamen Ratchev wrote:
>
>
>
>
>
> > Best would be to add the rank to the select list of the final pivot query:
>
> > DECLARE @pivot_query NVARCHAR(2000);
> > SET @pivot_query =
> > N'SELECT sort, reg, ' + @pivot_cols +
> >        N',ROW_NUMBER() OVER(ORDER BY sort) AS rn ' +
> >        N',RANK() OVER(ORDER BY sort) AS rk ' +
> > N'FROM (SELECT sort, reg, ' +
> >               N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME), 6),
> > 6) AS year_month, ' +
> >               N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL(5,
> > 2)) AS perc ' +
> >        N'FROM #temp1) AS F ' +
> > N'PIVOT ' +
> > N'(MAX(perc) FOR year_month IN (' + @pivot_cols + ')) AS P ' +
> > N'ORDER BY sort;';
>
> > --
> > Plamen Ratchevhttp://www.SQLStudio.com
>
> Okay got it but i had to change the order by Reg instead of using Sort
> now it's coming out right.  Can't wait to get that book.  Thanks again!- Hide quoted text -
>
> - Show quoted text -

Back again I realized this ranking order is for the entire row. Is
there a way I can rank each month? So in between each month would be
the rank for that month. Is that possible with this data?


DECLARE @pivot_cols NVARCHAR(1000);
SELECT @pivot_cols =
STUFF((SELECT '],[' + year_month
FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
CAST(dowrdt AS DATETIME),
6), 6),
CONVERT(CHAR(7), CAST(dowrdt AS
DATETIME), 126)
FROM #tempCnt) AS T(year_month, sort)
ORDER BY sort
FOR XML PATH('')
), 1, 2, '') + ']';

DECLARE @pivot_query NVARCHAR(2000);
SET @pivot_query =
N'SELECT sort, reg, ' + @pivot_cols +
N',ROW_NUMBER() OVER(ORDER BY Sort) AS rn ' +
N',RANK() OVER(ORDER BY Reg) AS rk ' +
N'FROM (SELECT sort, reg, ' +
N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME),
6),
6) AS year_month, ' +
N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL
(5,
2)) AS perc ' +
N'FROM #tempCnt) AS F ' +
N'PIVOT ' +
N'(MAX(perc) FOR year_month IN (' + @pivot_cols + ')) AS P ' +
N'ORDER BY Sort;';

EXEC(@pivot_query);

Sort Reg Nov08 rk Dec08 rk Jan09 rk Feb09 Mar09
Apr09 May09 Jun09 July09
1 NAT 11.04 12.05 14.66 14.10 13.98 14.57 15.02 15.06 16.40
A BOS 8.94 10.37 11.88 11.68 11.83 12.08 11.88 12.52 13.55
B NYC 8.28 11.58 15.38 15.51 14.81 15.27 16.14 16.65 17.68
C PHI 11.96 13.66 15.46 13.91 14.05 14.74 15.79 16.75 18.19
D ATL 10.93 11.13 14.40 13.72 14.44 14.97 15.07 15.15 16.34
E CHI 10.57 12.10 14.34 13.65 13.56 14.06 14.38 14.18 15.76
G KCM 8.03 8.56 10.09 10.91 10.63 11.55 11.35 11.22 12.62
H DAL 10.03 10.32 12.49 12.22 11.81 12.41 12.95 12.98 13.81
I DEN 12.70 13.17 16.96 15.38 15.24 16.76 17.51 17.29 20.64
J SFO 14.38 13.86 17.44 17.24 15.84 16.67 17.52 16.63 18.54
K SEA 14.93 16.52 19.80 17.18 18.01 18.23 18.22 18.53 19.64

 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
JJ297

External


Since: Feb 01, 2008
Posts: 51



(Msg. 33) Posted: Thu Dec 11, 2008 9:05 am
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Dec 11, 10:58 am, Plamen Ratchev wrote:
> Yes, you can add rank for each month column, you just need to add
> different column list for the SELECT clause:
>
> DECLARE @pivot_cols NVARCHAR(1000);
> SELECT @pivot_cols =
> STUFF((SELECT '],[' + year_month
>      FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
>                                  CAST(dowrdt AS DATETIME), 6), 6),
>                            CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
>            FROM #tempCnt) AS T(year_month, sort)
>      ORDER BY sort
>      FOR XML PATH('')
>      ), 1, 2, '') + ']';
>
> DECLARE @cols NVARCHAR(1000);
> SELECT @cols =
> STUFF((SELECT '],[' + year_month +
>                '],RANK() OVER(ORDER BY [' + year_month +
>                ']) AS [rank for ' + year_month
>      FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
>                                  CAST(dowrdt AS DATETIME), 6), 6),
>                            CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
>            FROM #tempCnt) AS T(year_month, sort)
>      ORDER BY sort
>      FOR XML PATH('')
>      ), 1, 2, '') + ']';
>
> DECLARE @pivot_query NVARCHAR(2000);
> SET @pivot_query =
> N'SELECT sort, reg, ' + @cols +
>         N',ROW_NUMBER() OVER(ORDER BY Sort) AS rn ' +
>         N',RANK() OVER(ORDER BY Reg) AS rk ' +
> N'FROM (SELECT sort, reg, ' +
>                N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME),
> 6),
> 6) AS year_month, ' +
>                N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL
> (5,
> 2)) AS perc ' +
>         N'FROM #tempCnt) AS F ' +
> N'PIVOT ' +
> N'(MAX(perc) FOR year_month IN (' + @pivot_cols + ')) AS P ' +
> N'ORDER BY Sort;';
>
> EXEC(@pivot_query);
>
> --
> Plamen Ratchevhttp://www.SQLStudio.com

This worked. Thanks so much. I'm so sorry to bother you with this
but I've never done Pivot's and it's complicated. My boss said I
should get a SQL 2005 book instead of 2008 as we're not changing over
to 2008 until another year. Do you have a good one in mind for SQL?
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
JJ297

External


Since: Feb 01, 2008
Posts: 51



(Msg. 34) Posted: Thu Dec 11, 2008 9:20 am
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Dec 11, 12:13 pm, Plamen Ratchev wrote:
> You can get those two books:
> Inside SQL Server 2005: T-SQL Querying
> Inside SQL Server 2005: T-SQL Programming
>
> Also, the book Expert SQL Server 2005 Development is very good. Best is
> to go to a local book store and review books, to find appropriate level
> and content you feel comfortable with.
>
> The book for T-SQL Fundamentals is excellent. Even labeled for SQL
> Server 2008, about 95% applies to SQL Server 2005 (and version specific
> content is noted).
>
> --
> Plamen Ratchevhttp://www.SQLStudio.com

Okay thanks for the book titles will look them up on Amazon now and
head to the bookstore to see which ones to get.

Got another question about Pivot's

Instead of rank for + year_month how can I have it say year_month
rank?

Also I tried to add two more columns next to each month which are icnt
and tcnt but don't know where to put them on the pivot to come out.

so I would have:

Sort Reg Nov 07 Nov07 Rank Nov iCnt Nov tCnt etc...
1 NAT 11.04 6 4559 7765
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
JJ297

External


Since: Feb 01, 2008
Posts: 51



(Msg. 35) Posted: Thu Dec 11, 2008 10:41 am
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

On Dec 11, 1:16 pm, Plamen Ratchev wrote:
> To change the alias for the ranking column, simply adjust the following
> section:
>
> DECLARE @cols NVARCHAR(1000);
> SELECT @cols =
> STUFF((SELECT '],[' + year_month +
>                '],RANK() OVER(ORDER BY [' + year_month +
>                ']) AS [' + year_month + ' rank'
>      FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
>                                  CAST(dowrdt AS DATETIME), 6), 6),
>                            CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
>            FROM #tempCnt) AS T(year_month, sort)
>      ORDER BY sort
>      FOR XML PATH('')
>      ), 1, 2, '') + ']';
>
> As far as adding the 'icnt' and 'tcnt' columns to the pivot output, you
> cannot do that using the PIVOT operator, because it supports pivoting on
> only one value (in your case that is 'perc'). The pivoting method has to
> be changed to use multiple CASE expressions. This allows to pivot on
> multiple values.
>
> DECLARE @pivot_cols NVARCHAR(MAX);
> SELECT @pivot_cols =
> STUFF((SELECT ',MAX(CASE WHEN year_month = ''' + year_month +
>                ''' THEN perc END) AS [' + year_month + ']' +
>                ',RANK() OVER(ORDER BY MAX(CASE WHEN year_month = ''' +
> year_month +
>                ''' THEN perc END)) AS [' + year_month + ' rank]' +
>                ',SUM(CASE WHEN year_month = ''' + year_month +
>                ''' THEN icnt END) AS [' + year_month + ' icnt]' +
>                ',SUM(CASE WHEN year_month = ''' + year_month +
>                ''' THEN tcnt END) AS [' + year_month + ' tcnt]'
>      FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
>                                  CAST(dowrdt AS DATETIME), 6), 6),
>                            CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
>            FROM #tempCnt) AS T(year_month, sort)
>      ORDER BY sort
>      FOR XML PATH('')
>      ), 1, 1, '');
>
> DECLARE @pivot_query NVARCHAR(MAX);
> SET @pivot_query =
> N'SELECT sort, reg, ' + @pivot_cols +
>         N',ROW_NUMBER() OVER(ORDER BY Sort) AS rn ' +
>         N',RANK() OVER(ORDER BY Reg) AS rk ' +
> N'FROM (SELECT sort, reg, icnt, tcnt, dowrdt, ' +
>                N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME), 6),
> 6) AS year_month, ' +
>                N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL(5,
> 2)) AS perc ' +
>         N'FROM #tempCnt) AS F ' +
> N'GROUP BY sort, reg ' +
> N'ORDER BY sort;';
>
> EXEC(@pivot_query);
>
> --
> Plamen Ratchevhttp://www.SQLStudio.com

Thanks this works just the way I wanted it. Looking up Pivoting on
multiple columns until I get my books. Thanks again for all of your
help!
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
Plamen Ratchev

External


Since: Aug 20, 2008
Posts: 672



(Msg. 36) Posted: Thu Dec 11, 2008 10:58 am
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

Yes, you can add rank for each month column, you just need to add
different column list for the SELECT clause:

DECLARE @pivot_cols NVARCHAR(1000);
SELECT @pivot_cols =
STUFF((SELECT '],[' + year_month
FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
CAST(dowrdt AS DATETIME), 6), 6),
CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
FROM #tempCnt) AS T(year_month, sort)
ORDER BY sort
FOR XML PATH('')
), 1, 2, '') + ']';

DECLARE @cols NVARCHAR(1000);
SELECT @cols =
STUFF((SELECT '],[' + year_month +
'],RANK() OVER(ORDER BY [' + year_month +
']) AS [rank for ' + year_month
FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
CAST(dowrdt AS DATETIME), 6), 6),
CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
FROM #tempCnt) AS T(year_month, sort)
ORDER BY sort
FOR XML PATH('')
), 1, 2, '') + ']';

DECLARE @pivot_query NVARCHAR(2000);
SET @pivot_query =
N'SELECT sort, reg, ' + @cols +
N',ROW_NUMBER() OVER(ORDER BY Sort) AS rn ' +
N',RANK() OVER(ORDER BY Reg) AS rk ' +
N'FROM (SELECT sort, reg, ' +
N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME),
6),
6) AS year_month, ' +
N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL
(5,
2)) AS perc ' +
N'FROM #tempCnt) AS F ' +
N'PIVOT ' +
N'(MAX(perc) FOR year_month IN (' + @pivot_cols + ')) AS P ' +
N'ORDER BY Sort;';

EXEC(@pivot_query);

--
Plamen Ratchev
http://www.SQLStudio.com
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
Plamen Ratchev

External


Since: Aug 20, 2008
Posts: 672



(Msg. 37) Posted: Thu Dec 11, 2008 12:13 pm
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

You can get those two books:
Inside SQL Server 2005: T-SQL Querying
Inside SQL Server 2005: T-SQL Programming

Also, the book Expert SQL Server 2005 Development is very good. Best is
to go to a local book store and review books, to find appropriate level
and content you feel comfortable with.

The book for T-SQL Fundamentals is excellent. Even labeled for SQL
Server 2008, about 95% applies to SQL Server 2005 (and version specific
content is noted).

--
Plamen Ratchev
http://www.SQLStudio.com
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
Plamen Ratchev

External


Since: Aug 20, 2008
Posts: 672



(Msg. 38) Posted: Thu Dec 11, 2008 1:16 pm
Post subject: Re: Dynamic SQL [Login to view extended thread Info.]
Archived from groups: per prev. post (more info?)

To change the alias for the ranking column, simply adjust the following
section:

DECLARE @cols NVARCHAR(1000);
SELECT @cols =
STUFF((SELECT '],[' + year_month +
'],RANK() OVER(ORDER BY [' + year_month +
']) AS [' + year_month + ' rank'
FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
CAST(dowrdt AS DATETIME), 6), 6),
CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
FROM #tempCnt) AS T(year_month, sort)
ORDER BY sort
FOR XML PATH('')
), 1, 2, '') + ']';

As far as adding the 'icnt' and 'tcnt' columns to the pivot output, you
cannot do that using the PIVOT operator, because it supports pivoting on
only one value (in your case that is 'perc'). The pivoting method has to
be changed to use multiple CASE expressions. This allows to pivot on
multiple values.

DECLARE @pivot_cols NVARCHAR(MAX);
SELECT @pivot_cols =
STUFF((SELECT ',MAX(CASE WHEN year_month = ''' + year_month +
''' THEN perc END) AS [' + year_month + ']' +
',RANK() OVER(ORDER BY MAX(CASE WHEN year_month = ''' +
year_month +
''' THEN perc END)) AS [' + year_month + ' rank]' +
',SUM(CASE WHEN year_month = ''' + year_month +
''' THEN icnt END) AS [' + year_month + ' icnt]' +
',SUM(CASE WHEN year_month = ''' + year_month +
''' THEN tcnt END) AS [' + year_month + ' tcnt]'
FROM (SELECT DISTINCT RIGHT(CONVERT(VARCHAR(9),
CAST(dowrdt AS DATETIME), 6), 6),
CONVERT(CHAR(7), CAST(dowrdt AS DATETIME), 126)
FROM #tempCnt) AS T(year_month, sort)
ORDER BY sort
FOR XML PATH('')
), 1, 1, '');

DECLARE @pivot_query NVARCHAR(MAX);
SET @pivot_query =
N'SELECT sort, reg, ' + @pivot_cols +
N',ROW_NUMBER() OVER(ORDER BY Sort) AS rn ' +
N',RANK() OVER(ORDER BY Reg) AS rk ' +
N'FROM (SELECT sort, reg, icnt, tcnt, dowrdt, ' +
N'RIGHT(CONVERT(VARCHAR(9), CAST(dowrdt AS DATETIME), 6),
6) AS year_month, ' +
N'CAST((1.0 * icnt / NULLIF(tcnt, 0) * 100) AS DECIMAL(5,
2)) AS perc ' +
N'FROM #tempCnt) AS F ' +
N'GROUP BY sort, reg ' +
N'ORDER BY sort;';

EXEC(@pivot_query);

--
Plamen Ratchev
http://www.SQLStudio.com
 >> Stay informed about: Dynamic SQL 
Back to top
Login to vote
Display posts from previous:   
Related Topics:
Dynamic date range for each row? - Hi, I'm trying to group data by date range, but each row of data could have a different date range based on a variable. I want to say "look at the date range the paste five orders were placed" for each row individually. As an example, think o...

Can't Auto-Start Agent - I have a SQL Server 2000 that failed to start after a Windows reboot. Agent properties are checked to auto start if stopped. Under the Agent Error Log, I have the following data: Information: SQL Agent stopping because of Windows shutdown. SQL Agent..

Seek method, table-direct, and sql server2005 - From what I've read in the docs, ado.net currently supports opening sql server ce tables in table-direct mode and performing Seek operations on them (using SqlCeDataReader), but not on the full-blown sql server. Is this (will this be) still true with...

pass hash (#) table with different structure to stored pro.. - Dear Techies, I making one stored procedure, which does some operation based on an interface hash (#) table ---- name #mydata. This stored has two section of code (seperated by parameter value 0 and 1) But hash table #mydata (same name) number/name of....

Datatype - I am using Visual Studio .NET 2003 with SQL Server 2000. I am trying to insert the date and time into a SQL database by using hour(now). I am having a hard time trying to figure out which datatype to use in SQL to store this value. I have tried using..
   Database Help (Home) -> General Discussions All times are: Pacific Time (US & Canada)
Goto page Previous  1, 2, 3
Page 3 of 3

 
You can post new topics in this forum
You can reply to topics in this forum
You can edit your posts in this forum
You can delete your posts in this forum
You can vote in polls in this forum



[ Contact us | Terms of Service/Privacy Policy ]