具有月份分组的垂直到水平表

时间:2016-08-23 14:50:00

标签: sql ms-access

长时间潜伏 - 第一次海报。

我是Access的新手并拥有一个数据表我试图通过查询进行操作。

当前观点:

ID  | $Value | Month   
1   | 184    | 10/1/2012    
1   | 186    | 11/1/2012     
1   | 176    | 12/1/2012     
1   | 183    | 1/1/2013     
1   | 192    | 2/1/2013     
1   | 201    | 3/1/2013     
1   | 183    | 4/1/2013     
1   | 179    | 5/1/2013     
1   | 177    | 6/1/2013     
1   | 135    | 7/1/2013     
1   | 202    | 8/1/2013     
1   | 188    | 9/1/2013     
2   | 258    | 5/1/2013     
2   | 126    | 6/1/2013     
2   | 236    | 7/1/2013     
2   | 367    | 8/1/2013     
2   | 450    | 9/1/2013     
2   | 186    | 10/1/2013     
2   | 248    | 11/1/2013     
2   | 264    | 12/1/2013     
2   | 257    | 1/1/2014     
2   | 264    | 2/1/2014     
2   | 138    | 3/1/2014     
2   | 264    | 4/1/2014  

所需的结局视图

ID | Month 1 | Month 2 | Month 3 | Month 4 | Month 5 | ... | Month 12    
1  | 184     | 186     | 176     | 183     | 192     | ... | 188    
2  | 258     | 126     | 236     | 367     | 450     | ... | 264

我试图在Access中转置数据,以便每个ID只有一行并对这些月进行分组(始终标记为'第1个月和第39个月,'第2个月'等等......)我只希望看到12列的月份(每个月和每年都不是一列)。因此,在上面的示例ID 1中,尽管每个ID的月份和年份不同,但是第1个月是184而ID 2,第1个月是258。

非常感谢任何指导/帮助。

3 个答案:

答案 0 :(得分:1)

I'm not too familiar with the graphical query editor interface, but you can definitely do this in SQL using the TRANSFORM and PIVOT features along with the month() function. In fact, in the graphical interface, you may just be missing the month() function. I believe the sql version would look like this:

TRANSFORM Max([Current View].[$Value])
SELECT  [Current View].[ID] 
from [Current View] inner join  
     ( select tbl1.[ID], min(cdate(tbl1.[Month])) as minDate
       from [Current View] as tbl1
       group by tbl1.[ID]) as earliestDate on [Current View].[ID] = earliestDate.[ID]
Where datediff("m", earliestDate.minDate, [Current View].[Month])<=12
group by [Current View].[ID]
PIVOT (datediff("m", earliestDate.minDate, [Current View].[Month]) +1 )
;

EDIT: Added on logic to define months based on the starting month for each ID, and restrict to only the 12 following months.

答案 1 :(得分:1)

考虑到每个ID和月只有一个值,请使用FIRST汇总函数,而不是我的同事提议的SUMMAX

TRANSFORM FIRST([$Value]) 
SELECT [ID] 
FROM [Current View] 
GROUP BY [ID] 
PIVOT "Mo" & Month([Month])

如果你想要所有年份和月份(yyyy-mm)

TRANSFORM FIRST([$Value]) 
SELECT [ID] 
FROM [Current View] 
GROUP BY [ID] 
PIVOT (Year([Month]) & '-' & Month([Month])) 

答案 2 :(得分:0)

As has been suggested - a crosstab (pivot) query would work here:

TRANSFORM   Sum(sValue) AS SumOfsValue
SELECT      ID
FROM        Table1
GROUP       BY ID
PIVOT       "Mo" & Month([dMonth])

Is your 'Desired Ending View' correct?
e.g. You've got 188 for ID 1 in month 12 - shouldn't this be 176?