1

我有这样的专栏

    FIELDPID    FIELDNAME   VALUE
     12       COMPANY_NAME  Bristol bb
     12       CP_ID         47957
     12       CPID_TYPE         ORG
     67       COMPANY_NAME  PRODUCTS LTD
     67       CP_ID         47957
     67       CPID_TYPE     ORG
     69       COMPANY_NAME  PRODUCTS LTD
     69       CP_ID         47957
     69       CPID_TYPE     IND

我希望结果为

FIELDPID,COMPANY_NAME,CP_ID,CPID_TYPE

FIELDPID    COMPANY_NAME    CP_ID   CPID_TYPE
    12      Bristol bb      47957   ORG
    67      PRODUCTS LTD    47975   ORG

验证 cpid_type 只能是“org” 感谢 Arun 的帮助

4

2 回答 2

2

Use the PIVOT table operator:

SELECT *
FROM tablename AS t
PIVOT
(
   MAX(Value)
   FOR FieldName IN([COMPANY_NAME],
                    [CP_ID],
                    [CPID_TYPE])
) AS p;

Update:

If you want to add a condition for the CPID_TYPE you can do this:

WITH CTE AS
(
    SELECT *
    FROM tablename AS t
    PIVOT
    (
       MAX(Value)
       FOR FieldName IN([COMPANY_NAME],
                        [CP_ID],
                        [CPID_TYPE])
    ) AS p
) 
SELECT * 
FROM CTE
WHERE CPID_TYPE = 'ORG';
于 2013-11-04T09:16:41.590 回答
0

看起来你的数据有一点错误。的情况下

 13       CPID_TYPE         ORG

可以改为

 12       CPID_TYPE         ORG

结果查询将Mahmoud Gamal如前所述:

SELECT *
FROM tablename AS t
PIVOT
(
   MAX(Value)
   FOR FIELDPID IN([COMPANY_NAME],
                    [CP_ID],
                    [CPID_TYPE])
) AS p

结果将是正确的。PIVOT可在此处找到其他信息: http ://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

于 2013-11-04T09:24:38.947 回答