在sql中将行动态转置为列,无需将列/行值作为标题

时间:2017-10-11 10:27:18

标签: sql sql-server

我是SQL的初学者,但我不想使用代码来实现这一点,因为我研究过它可以通过SQL来实现。

查询

select 
    c.CLAIM_ID,
    e.CODE,
    e.DX_TYPE
from 
    claim_sub c,
    diagnosis_sub e
where 
    c.uid = e.DIAG_CLAIM_UID and
    --e.uid = f.DXINFO_DIAG_UID and
    c.claim_id in( 'IP0000013119','IP0000013124')

当前输出:

CLAIM_ID        DX_TYPE     CODE
-------------------------------------
IP0000013119    PRINCIPAL   M62.82
IP0000013119    SECONDARY   E55.9
IP0000013119    SECONDARY   M79.652
IP0000013119    SECONDARY   M79.651
IP0000013119    SECONDARY   M51.37
IP0000013119    SECONDARY   R20.0
IP0000013119    SECONDARY   R94.4
IP0000013119    SECONDARY   R79.89
IP0000013119    SECONDARY   R73.09
IP0000013124    PRINCIPAL   K52.9
IP0000013119    SECONDARY   E86.0
IP0000013124    SECONDARY   R10.9
IP0000013124    SECONDARY   R11.10
IP0000013124    SECONDARY   R63.8
IP0000013124    SECONDARY   R79.89

期望的输出:

Claim_ID    DX_TYPE1    CODE1   DX_TYPE2    CODE2   DX_TYPE3    CODE3   DX_TYPE4    CODE4   DX_TYPE5    CODE5   DX_TYPE6    CODE6   DX_TYPE7    CODE7   DX_TYPE8    CODE8   DX_TYPE9    CODE9
IP0000013119    PRINCIPAL   M62.82  SECONDARY   E55.9   SECONDARY   M79.652 SECONDARY   M79.651 SECONDARY   M51.37  SECONDARY   R20.0   SECONDARY   R94.4   SECONDARY   R79.89  SECONDARY   R73.09
IP0000013124    PRINCIPAL   K52.9   SECONDARY   E86.0   SECONDARY   R10.9   SECONDARY   R11.10  SECONDARY   R63.8   SECONDARY   R79.89      

1 个答案:

答案 0 :(得分:0)

由于您没有花费额外的努力为我们提供所用表格的ddl以及其中的一组测试数据,因此我无法在sql代码中为您提供问题的答案。然而,我可以给你一个关于交叉表和主题文章Jeff Moden的优秀文章的链接,这样你就可以完全研究和理解这个主题:Part 1& Part 2