Please start any new threads on our new site at http://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 group by and count(*)
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

cjcclee
Starting Member

33 Posts

Posted - 08/16/2013 :  13:30:56  Show Profile  Send cjcclee an AOL message  Reply with Quote
Hi, all,

Is there better way to do this instead of use seperate group by and count(*), then union each query? For example

Date attribute1 attribute2 attribute3
2013/08/01 value1 type1 something1
2013/07/01 value2 type2 somthing2

the final result want to be: count each year and month how many value1, value2, type1 type2 etc

Year Month Value1 value2 type1 type2 something1 something2 Grandtotal

Is better way to do this intead of different group by and count and union all queries? Thank you!




visakh16
Very Important crosS Applying yaK Herder

India
52326 Posts

Posted - 08/16/2013 :  14:03:34  Show Profile  Reply with Quote

SELECT YEAR([Date]) AS YrVal,
MONTH([Date]) AS MonthVal,
MAX(CASE WHEN attribute2 = 'type1' THEN attribute1 END) AS value1,
MAX(CASE WHEN attribute2 = 'type2' THEN attribute1 END) AS value2,
MAX(CASE WHEN attribute2 = 'type1' THEN attribute2 END) AS type1,
MAX(CASE WHEN attribute2 = 'type2' THEN attribute2 END) AS type2,
MAX(CASE WHEN attribute2 = 'type1' THEN attribute3 END) AS something1,
MAX(CASE WHEN attribute2 = 'type2' THEN attribute3 END) AS something2
FROM Table
GROUP BY YEAR([Date]),
MONTH([Date])


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

MuMu88
Aged Yak Warrior

549 Posts

Posted - 08/16/2013 :  14:08:22  Show Profile  Reply with Quote
You can use ROLLUP or GROUPING SETS as described here:
http://technet.microsoft.com/en-us/library/bb522495(v=sql.105).aspx
Go to Top of Page

cjcclee
Starting Member

33 Posts

Posted - 08/16/2013 :  15:12:48  Show Profile  Send cjcclee an AOL message  Reply with Quote
Thank you so much! It is nuch simply the code!
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000