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 |
|
DirkNiblick
Starting Member
2 Posts |
Posted - 2009-10-16 : 10:04:22
|
| I'm sorry if I duplicate someone's post but I've searched quite a bit for answers to my goal but have come up empty. I'm new to the forums as well so bear with me:I have three tables like this (sorry for the formatting):FramesID Name1 PS02 PS13 PS2...LPARSID Hostname FrameID1 app01 12 app02 13 app11 24 app12 2...LPARConfigsID LPARID Memory CPU ConfigDate1 1 8 2 3/1/20062 1 16 2 6/1/20063 1 16 4 9/1/20064 2 4 1 3/1/20065 2 4 2 9/1/2006...A Frame contains LPARS which each have different configurations in time. I would like to write a single query for SQL Server that would, for a given Frame.ID, return the sum of LPARConfigs.Memory and LPARConfigs.CPU for the latest LPARConfig record for each LPAR belonging to that Frame. For example, Frame #1 the answer would be 20 and 6 (summing the values from LPARConfigs #3 and #5). Any ideas? ...is it even possible? |
|
|
Ifor
Aged Yak Warrior
700 Posts |
Posted - 2009-10-16 : 10:59:57
|
| [code]-- *** Test Data ***DECLARE @LPars TABLE( [ID] int NOT NULL ,Hostname varchar(20) NOT NULL ,FrameID int NOT NULL)INSERT INTO @LParsSELECT 1, 'app01', 1UNION ALL SELECT 2, 'app02', 1UNION ALL SELECT 3, 'app11', 2UNION ALL SELECT 4, 'app12', 2DECLARE @LPARConfigs TABLE( [ID] int NOT NULL ,LPARID int NOT NULL ,Memory int NOT NULL ,CPU int NOT NULL ,ConfigDate datetime NOT NULL)INSERT INTO @LPARConfigsSELECT 1, 1, 8, 2, '20060301'UNION ALL SELECT 2, 1, 16, 2, '20060601'UNION ALL SELECT 3, 1, 16, 4, '20060901'UNION ALL SELECT 4, 2, 4, 1, '20060301'UNION ALL SELECT 5, 2, 4, 2, '20060901'-- *** End Test Data ***;WITH ConfigOrderAS( SELECT LPARID ,Memory ,CPU ,ROW_NUMBER() OVER (PARTITION BY LPARID ORDER BY ConfigDate DESC) AS RowNum FROM @LPARConfigs)SELECT P.FrameID ,SUM(C.Memory) AS Memory ,SUM(C.CPU) AS CPUFROM @LPars P JOIN ConfigOrder C ON P.[ID] = C.LPARID AND C.RowNum = 1 GROUP BY P.FrameID[/code] |
 |
|
|
DirkNiblick
Starting Member
2 Posts |
Posted - 2009-10-16 : 12:29:48
|
| Thank you Ifor for the great reply. I believe I understand what's going on there but what exactly does "ROW_NUMBER() OVER (PARTITION BY LPARID ORDER BY ConfigDate DESC) AS RowNum" do? |
 |
|
|
Ifor
Aged Yak Warrior
700 Posts |
Posted - 2009-10-19 : 06:32:04
|
| For each LPARID (PARTITION BY LPARID) it gives every row an unique number starting with 1 for the most recent ConfigDate (ConfigDate DESC).(If you run SELECT * FROM ConfigOrder you will see the result.)As you only want the most recent ConfigDate for each LPARID, the join then filters on RowNum = 1. (ie Any older rows are ignored.) |
 |
|
|
|
|
|
|
|