选择一个列标题相同名称并水平显示数据

时间:2017-07-04 16:23:52

标签: sql sql-server

我有两张桌子:

1-合同

    contracts_id  |  subject_contract  
    001           |  name              
    002           |  name                         

2-contracts_files

    contracts_id  |  file_data
    001           |  1image <varbinary(MAX)>
    002           |  1image <varbinary(MAX)>
    001           |  2image <varbinary(MAX)>
    002           |  2image <varbinary(MAX)>

需要像这样结果的SQL输出:

contracts_id  |  subject_contract  |  file_data   |  file_data 
001           |  name              |  1image      |  2image 
002           |  name              |  1image      |  2image 

我试试这个

SELECT Contracts.[contracts_id]  
      ,Contracts.[subject_contract]
      ,contracts_files.[filedata]


  FROM Contracts , contracts_files

  where contracts_files.contracts_id = Contracts.contracts_id

  AND Contracts.contracts_id=' 001 '

但结果是:

contracts_id  |  subject_contract  |  file_data  
    001       |  name              |  1image  
    001       |  name              |  2image    

那么我怎么能用&#39; FOR LOOP&#39;来创造它呢?或者使用&#39; CASE&#39; ?

2 个答案:

答案 0 :(得分:1)

您可以使用以下角色:

Select * from (
    SELECT c.[contracts_id]  
          ,c.[subject_contract]
          ,cf.[filedata]
          ,RN = Row_Number() over (partition by c.[Contracts_id] order by c.[contracts_id])
      FROM Contracts c join contracts_files cf
      ON cf.contracts_id = c.contracts_id
      ) a
      pivot (max(filedata) for RN in ([1],[2]) ) p

答案 1 :(得分:0)

如果您不喜欢枢轴,请使用旧方法(当某个变量= 1时)然后(某个值)。如果when不运行,则使用null,MAX()不会返回null。突出显示内部查询并运行该查询,以便在您感到好奇的情况下查看数据在变换中途的方式

SELECT
  contracts_id,
  subject_contract,
  MAX(CASE WHEN rown = 1 then file_data end) as file1,
  MAX(CASE WHEN rown = 2 then file_data end) as file2

FROM 
  (SELECT c.contracts_id, subject_contract, file_data, row_number() over (partition by c.[Contracts_id] order by c.[contracts_id]) as rown FROM contracts c INNER JOIN contracts_files cf ON cf.contracts_id = c.contracts_id) a
GROUP BY
  contracts_id, 
  subject_contract