3

我有 2 张桌子:

Table 1

id   question   customerId
1     bla1         1
2     bla2         2    

Table 2

id    customerId    Key         Value
1      1           firstname    John
2      1           lastname     Doe
3      2           firstname    Billy
4      2           lastname     Jones

我需要让我的gridview显示:

Row 1: John Doe        Bla1
Row 2: Billy Jones     Bla2

目前它显示:(但我不希望这样):

Row 1: John      Bla1
Row 2: Doe       Bla1
Row 3: Billy     Bla2
Row 4: Jones     Bla2

我想我已经尝试了一切,可以使用你的帮助!谢谢。

4

3 回答 3

3
SELECT  [firstname],[lastname], question
FROM
        (
            SELECT  a.question, b.[key], b.[value]
            FROM    Table1 a
                    INNER JOIN Table2 b
                        ON a.customerID = b.CustomerID
        ) org
        PIVOT
        (
            MAX([value])
            FOR [KEY] IN ([firstname],[lastname])
        ) pvt

输出

╔═══════════╦══════════╦══════════╗
║ FIRSTNAME ║ LASTNAME ║ QUESTION ║
╠═══════════╬══════════╬══════════╣
║ John      ║ Doe      ║ bla1     ║
║ Billy     ║ Jones    ║ bla2     ║
╚═══════════╩══════════╩══════════╝
于 2013-04-20T09:01:22.967 回答
0
SELECT [firstname],[lastname], question
FROM
(
    SELECT Q.ID, Question, Q.CUSTOMERID, KeyId, KeyValue 
    FROM QUESTION Q
            INNER JOIN CUSTOMERMAP C ON Q.CUSTOMERID=C.CUSTOMERID
) as Data
PIVOT
(
   MAX(KeyValue)
   FOR KeyId in ([firstname],[lastname])
) as PT;
于 2013-04-20T09:25:20.903 回答
0

使用以下查询选择绑定网格的数据:

SELECT 
    a.id, 
    a.Question,
    (SELECT Value + ' ' FROM Table2 b WHERE b.customerId=a.customerid 
        FOR XML PATH(''),type).value('.','nvarchar(max)') Value
FROM Table1 a
于 2013-04-20T09:28:28.123 回答