【问题标题】:How would I pivot this type of data in T-SQL?我将如何在 T-SQL 中旋转这种类型的数据?
【发布时间】:2017-01-20 10:53:53
【问题描述】:

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

 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'

【问题讨论】:

  • 不同?通过...分组?如果您向我们展示您的查询,将会很有帮助...
  • 我正在使用不同的。我添加了一个查询示例。我无法发布相同的查询。
  • 根据哪个规则ID 1 连接到“这是一个句子”,ID 2 连接到“...另一个...”和 ID 3 到 “第三个...”
  • 句子应该来自table4或t4。

标签: sql-server tsql pivot aggregate grouping


【解决方案1】:

您仍然可以尝试 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

【讨论】:

  • 但是它们都是不同的,因为每个 ID (1, 2, 3) 都有自己的一组对应的句子。
  • 是的,我想说您的解决方案也应该有效。但是你可以试试我的以防万一。顺便说一句,在您的示例中,您不需要 t5。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多