组合gridview行并消除重复

时间:2013-04-20 08:56:45

标签: c# asp.net sql sql-server-2008 pivot

我有两张桌子:

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

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

3 个答案:

答案 0 :(得分: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     ║
╚═══════════╩══════════╩══════════╝

答案 1 :(得分: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;

答案 2 :(得分: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