按ID分组,将其余列分成不同的列

时间:2015-12-17 19:19:45

标签: ms-access access-vba ms-access-2007

我正在尝试创建一个类似于以下示例的表格。

| SO_NUMBER | ORDER                      |
------------------------------------------
| 12345     | iphone5|1|500|APPLE        |
| 12345     | icase-blk|1|20|CaseCompany |
| 23411     | galaxy5|1|500|Samsung      |
| 23411     | galaxy-blk|1|20|CaseCompany|

将其转换为此..

| SO_NUMBER | ORDER_1                    | ORDER_2
-----------------------------------------------------------------------
| 12345     | iphone5|1|500|APPLE        | icase-blk|1|20|CaseCompany
| 23411     | galaxy5|1|500|Samsung      | galaxy-blk|1|20|CaseCompany

我不确定从哪里开始,我可以按SO_Number进行分组,但不确定是否需要创建临时表。我一直在搜索,我能找到的就是将它们与逗号分组,但这对此无效。

编辑: 我开始查看Option Compare Database RunningCount脚本来完成我的要求。它大部分都有效。

Option Compare Database
Option Explicit
Public wName As String
Public wRuningCount As Long
Function GetRunCount(Name1) As Long
If wName = Name1 Then
wRuningCount = wRuningCount + 1
Else
wName = Name1
wRuningCount = 1
End If
GetRunCount = wRuningCount
End Function

但现在我得到了

| SO_NUMBER | ORDER_1 | ORDER_3 | 

而不是

| SO_NUMBER | ORDER_1 | ORDER_2 |

自动脚本设置的查询如下..

TRANSFORM First([123].ORDER) AS FirstOfORDER
SELECT [123].SO_NUMBER
FROM 123
GROUP BY [123].SO_NUMBER
PIVOT [123].GetRunCount;

1 个答案:

答案 0 :(得分:0)

使用“查询向导”创建交叉表查询。以下是一个示例:

create table Employee( emp_id int not null Primary key,
name varchar(50) null
);

insert into Employee values(1,'ABC')
insert into Employee values(2,'XYZ')
insert into Employee values(3,'EFG')

Create table Wages (
wage_id int not null primary key,
emp_id int null,
month int null,
year int null,
wage int    null,
paid int null
)


 insert into wages values(1,1,11,2015,2000,2000)
 insert into wages values(2,2,11,2015,1000,1000)
 insert into wages values(3,3,11,2015,1500,1700)
 insert into wages values(4,1,12,2015,2000,2000)
 insert into wages values(5,3,12,2015,1500,0   )

-------------Query to get the desired output-----------
SELECT e.Name, ISNULL(w.wage, 0), ISNULL(w.paid, 0)
FROM Employee e
LEFT JOIN Wages w
ON e.emp_id = w.emp_id 
AND [month] = 11 AND [YEAR] = 2015
WHERE w.wage IS NULL OR w.wage <> w.paid