使用列标题取消隐藏 - 单行

问题描述 投票:0回答:2

我有一些关于某个人的信息,我希望以两行而不是多列显示。

我希望列为“ColumnName”和“ColumnData”

这是我的返回单行的查询:

SELECT C.CUSTOMER_NAME
      ,CC.CONTACT_NAME
      ,CC.TELEPHONE
      ,CC.FAX
      ,CC.CONTACT_INITIALS
      ,CC.CONTACT_FIRSTNAME
      ,CC.EMAIL
      ,CC.CONTACT_DEAR
      ,CC.NUMERIC_PHONE_NO
      ,CC.TELEPHONE_NUMBER2
      ,CC.MOBILE_TELEPHONE
      ,CC.NUMERIC_TELEPHONE2
      ,CC.NUMERIC_MOBILE
      ,CC.NUMERIC_FAX
      ,CC.CONTACT_FULL_NAME
      ,CONTACT_MIDDLE_NAMES
FROM table C 
INNER JOIN table CC
ON C.column = CC.column
WHERE C.column = @CustomerAccount

我试图解开这个并且没有设法让它工作,因为没有聚合并且每行只有一个值。

虽然我可以从sys.columns获取列名称,但我无法将它们与表格相关联,也不得不将它们取消。

有没有办法将这一行变成两列,包括列名和该列中的数据?

任何帮助,链接或指导将不胜感激。

谢谢

将。

sql-server tsql unpivot
2个回答
2
投票

你可以像下面的查询一样使用UNPIVOT

;WITH cte 
     AS (SELECT C.customer_name, 
                CC.contact_name, 
                CC.telephone, 
                CC.fax, 
                CC.contact_initials, 
                CC.contact_firstname, 
                CC.email, 
                CC.contact_dear, 
                CC.numeric_phone_no, 
                CC.telephone_number2, 
                CC.mobile_telephone, 
                CC.numeric_telephone2, 
                CC.numeric_mobile, 
                CC.numeric_fax, 
                CC.contact_full_name, 
                contact_middle_names 
         FROM   table C 
                INNER JOIN table CC 
                        ON C.COLUMN = CC.COLUMN 
         WHERE  C.COLUMN = @CustomerAccount) 
SELECT u.x AS ColumnName, 
       u.y AS ColumnValue 
FROM   cte s 
       UNPIVOT ( [y] 
               FOR [x] IN (customer_name, 
                           contact_name, 
                           telephone, 
                           fax, 
                           contact_initials, 
                           contact_firstname, 
                           email, 
                           contact_dear, 
                           numeric_phone_no, 
                           telephone_number2, 
                           numeric_mobile, 
                           numeric_fax, 
                           contact_full_name, 
                           contact_middle_names) ) u; 

Online Demo


0
投票

这是一种技术,可以“动态”地移动几乎任何表,视图或即席查询,而无需实际使用动态SQL

显然,UNPIVOT会更高效,但您不必在此指定列名。

Select C.*
 From  ( Your table or Query Here ) A
 Cross Apply ( values (cast((Select A.* for XML RAW) as xml))) B(XMLData)
 Cross Apply (
               Select Item  = xAttr.value('local-name(.)', 'varchar(100)')
                     ,Value = xAttr.value('.','varchar(max)')
                From  XMLData.nodes('//@*') xNode(xAttr)
                Where xAttr.value('local-name(.)','varchar(100)') not in ('Columns','ToExclude')
             ) C

我应该注意到WHERE是可选的。

© www.soinside.com 2019 - 2024. All rights reserved.