如何在T-SQL中转换此类数据?

时间:2016-09-12 22:46:12

标签: sql-server tsql pivot aggregate grouping

我有一个查询可以生成这样的结果

 ID | Column2 | Sentence
----|---------|---------
1   | SameVal |This is a sentence
1   | SameVal |This is another unique sentence
1   | SameVal |A third unique sentence
2   | SameVal |This is a sentence
2   | SameVal |This is another unique sentence
2   | SameVal |A third unique sentence
3   | SameVal |This is a sentence
3   | SameVal |This is another unique sentence
3   | SameVal |A third unique sentence

我是否有可能以某种方式调整此数据,以便我的结果如此

 ID | Column2 | Sentence
----|---------|---------
1   | SameVal |This is a sentence
2   | SameVal |This is another unique sentence
3   | SameVal |A third unique sentence

以下查询:

SELECT DISTINCT 
    t1.ID, t2.Department, t1.ReportMonth, t2.Supplier,
    t1.RepID, t1.CustomerID, t4.Sentence
FROM 
    table1 t1
JOIN 
    table2 t2 ON t2.ID = t1.ID
JOIN 
    table3 rt ON rt.LookupCd = t1.ProgramCD
JOIN 
    table4 t4 ON t4.CustomerID = t1.CustomerID
LEFT JOIN 
    table5 t5 ON t1.CustomerID = t5.CustomerID
WHERE
    t1.code = 'ax' AND
    t2.program = 'qx' AND
    t1.date = '7/7/12'

1 个答案:

答案 0 :(得分:0)

你仍然可以尝试DISTINCT或GROUP BY:

SELECT DISTINCT * FROM
(
    SELECT t1.ID,t2.Department,t1.ReportMonth,t2.Supplier,t1.RepID,t1.CustomerID,t4.Sentence
    FROM table1 t1
    JOIN table2 t2 ON t2.ID = t1.ID
    JOIN table3 rt ON rt.LookupCd = t1.ProgramCD
    JOIN table4 t4 ON t4.CustomerID = t1.CustomerID
    LEFT JOIN table5 t5 ON t1.CustomerID = t5.CustomerID
    WHERE
        t1.code = 'ax' AND
        t2.program = 'qx' AND
        t1.date = '7/7/12'
) t

SELECT t1.ID,t2.Department,t1.ReportMonth,t2.Supplier,t1.RepID,t1.CustomerID,t4.Sentence
FROM table1 t1
JOIN table2 t2 ON t2.ID = t1.ID
JOIN table3 rt ON rt.LookupCd = t1.ProgramCD
JOIN table4 t4 ON t4.CustomerID = t1.CustomerID
LEFT JOIN table5 t5 ON t1.CustomerID = t5.CustomerID
WHERE
    t1.code = 'ax' AND
    t2.program = 'qx' AND
    t1.date = '7/7/12'
GROUP BY t1.ID,t2.Department,t1.ReportMonth,t2.Supplier,t1.RepID,t1.CustomerID,t4.Sentence