Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
sp22403
Starting Member
3 Posts |
Posted - 2011-08-01 : 11:01:50
|
| I need help in writing a SQL query to retrieve the data in the following format.Col1 Col2XXX 06-22-2011XXX 07-18-2011YYY 07-06-2011YYY 07-18-2011NOTE: The result returns the unique user count per month and returns all the other months in the result set even if there is no data.Query Result2011 Jan 02011 Feb 0...2011 Jun 12011 Jul 22011 Aug 0...2011 Nov 02011 Dec 0 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-01 : 12:51:28
|
| [code];With Month_CTE(mnth)AS(SELECT 1UNION ALLSELECT mnth + 1FROM Month_CTEWHERE mnth+1<=12)SELECT t.Yr,t.mnth,COALESCE(f.DisCnt,0) AS DistCntFROM(SELECT t1.Yr,c.mnthFROM (SELECT DISTINCT YEAR(Col2) AS Yr FROM Table) t1CROSS JOIN Month_CTE c)tLEFT JOIN (SELECT YEAR(Col2) AS Yr,MONTH(Col2) AS mnth,COUNT(DISTINCT Col1) AS DisCnt FROM Table GROUP BY YEAR(Col2),MONTH(Col2))fON f.Yr = t.YrAND f.mnth = t.mnth[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
sp22403
Starting Member
3 Posts |
Posted - 2011-08-01 : 14:56:03
|
| Thanks for the quick reply. That's exactly what I needed. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-02 : 00:59:59
|
| welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|