将行值更改为访问查询中的列值

时间:2015-10-14 20:45:19

标签: sql ms-access

我目前的行值包含可以更改列值的重复项,但我希望我的列名称为dependency1dependency2dependency3等。

目前我的结果是:

idea_code   Network Products    Telehealth  Test1 Test23

I0000555    Network Products            
I0000556                         Telehealth Test1   Test23

但我希望我的专栏看起来像

Idea_Code    Dependency1       dependency2    dependency3 ----
I0000555     Network Products           
I0000556     Telehealth        Test1          Test23

我当前的访问查询是:

TRANSFORM First(DA.dependency_name) AS dependency_name

SELECT DA.idea_code

FROM tbl_IdeasDependencies AS DA

GROUP BY DA.idea_code

PIVOT DA.dependency_name;

1 个答案:

答案 0 :(得分:0)

考虑以下解决方案,该解决方案涉及使用派生表子查询进行查询的组。使用DependencyCountidea_code,主查询将使用条件IIF()转置为编号的依赖关系字段:

SELECT idea_code, 
       Max(IIF(DependencyCount = 1, dependency_name, "")) As Dependency1,
       Max(IIF(DependencyCount = 2, dependency_name, "")) As Dependency2,
       Max(IIF(DependencyCount = 3, dependency_name, "")) As Dependency3
       ...
FROM
    (
      SELECT  t1.idea_code,         
              t1.dependency_name,
              (SELECT Count(*) 
               FROM tbl_IdeasDependencies t2 
               WHERE t1.idea_code = t2.idea_code 
               AND t1.dependency_name >= t2.dependency_name) As DependencyCount
      FROM tbl_IdeasDependencies t1
)
GROUP BY idea_code

输出

idea_code   Dependency1         Dependency2     Dependency3
I0000555    Network Products        
I0000556    Telehealth          Test1           Test23

请注意此解决方案,dependency_name值按字母顺序排列,每列idea_code