如何在SQL Server中格式化输出表?

时间:2018-01-30 13:46:20

标签: sql sql-server pivot ssms

运行此查询后

SELECT Title , 
CASE WHEN fieldName = 'Supplier Name' THEN fieldvalue
END AS 'Supplier Name',
CASE WHEN fieldname = 'Legal Agreement Name' THEN fieldValue 
END AS 'Legal Agreement Name'
FROM PCM_MultiItems_Metadata
WHERE PROFILEID =254 
      and fieldname in ('Creator Contact Name','Supplier Name','Legal Agreement Name');

我正在

enter image description here

我在sql server中为不同资产的不同属性生成了这个表

I have this table generated in sql server for different properties of different assets

如何在sql中格式化这个表,以便我得到像Title这样的表成为我的第一列,供应商名称和法定名称分别是我的第2和第3列

我生成该表的SQL查询是

SELECT Title, FieldName, Fieldvalue 
from PCM_MultiItems_Metadata 
WHERE PROFILEID =254 
  and fieldname in ('Creator Contact Name','Supplier Name','Legal Agreement Name');

我想要一个输出,例如

Title      | Supplier Name              | Legal Agreement Name
231457       Bay VALLEY                   IMAGE AND DIGITAL AGREEMENT
232058       BUCKHEAD MEAT;NEWPORT MEAT   SYSCO MEAT BRAND GUDILINE

3 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

SELECT Title , 
CASE WHEN fieldName = 'Supplier Name' THEN fieldvalue
END AS 'Supplier Name',
CASE WHEN fieldname = 'Legal Agreement Name' THEN fieldValue 
END AS 'Legal Agreement Name'
FROM PCM_MultiItems_Metadata
WHERE PROFILEID =254 
      and fieldname in ('Creator Contact Name','Supplier Name','Legal Agreement Name');

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT
    t1.Title,
    t1.FieldValue as [Supplier Name],
    t2.FieldValue as [Legal Agreement Name]
FROM PCM_MultiItems_Metadata t1
INNER JOIN PCM_MultiItems_Metadata t2 on t2.Title= t1.Title
WHERE t1.FieldName = 'Supplier Name'
AND t2.FieldName = 'Legal Agreement Name'

这适用于您提供的源数据的有限快照。如果FieldName还有其他列或值,则需要相应地进行调整。

修改
调整为举例说明如何使用FieldName的更多值。

SELECT DISTINCT
    t1.Title,
    t1.FieldValue as [Supplier Name],
    t2.FieldValue as [Legal Agreement Name],
    t3.FieldValue as [Field 3],
    t4.FieldValue as [Field 4],
FROM PCM_MultiItems_Metadata t1
INNER JOIN PCM_MultiItems_Metadata t2 on t2.Title= t1.Title
INNER JOIN PCM_MultiItems_Metadata t3 on t3.Title= t1.Title
INNER JOIN PCM_MultiItems_Metadata t4 on t4.Title= t1.Title
WHERE t1.FieldName = 'Supplier Name'
AND t2.FieldName = 'Legal Agreement Name'
AND t3.FieldName = 'Field 3',
AND t4.FieldName = 'Field 4'

这是一个基于FieldName的静态值集的静态解决方案。

答案 2 :(得分:0)

使用条件聚合,您可以执行以下操作。

sudo apt-get install php7.0-soap

sudo systemctl restart php7.0-fpm
sudo systemctl restart nginx