Sql server 如何在T-SQL中透视这种类型的数据?
我有一个查询,它生成如下结果Sql server 如何在T-SQL中透视这种类型的数据?,sql-server,tsql,pivot,aggregate,grouping,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
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'
您仍然可以通过以下方式尝试使用DISTINCT或GROUP:
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
或
您仍然可以通过以下方式尝试使用DISTINCT或GROUP:
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
或
不同的分组?如果您向我们展示您的查询,将非常有用…我使用的是distinct。我添加了一个查询示例。我不能发布相同的查询。根据哪个规则,ID 1连接到“这是一个句子”,ID 2连接到“…另一个…”,ID 3连接到“第三个…”?这个句子应该来自表4或t4。不同?分组?如果您向我们展示您的查询,将非常有用…我使用的是distinct。我添加了一个查询示例。我不能发布相同的查询。根据哪个规则,ID 1连接到“这是一个句子”,ID 2连接到“…另一个…”,ID 3连接到“第三个…”?这个句子应该来自表4或t4。但是它们都是不同的,因为每个ID(1,2,3)都有自己的对应句子集。是的,我想说你的解决方案也应该有效。但你可以试试我的以防万一。顺便说一句,在你的例子中,你不需要t5。但是它们都是不同的,因为每个ID(1,2,3)都有自己的一组对应的句子。是的,我想说你的解决方案也应该有效。但你可以试试我的以防万一。顺便说一句,在你的例子中,你不需要t5。