1

我有如下数据表

Prod-Code Name              Rollup1 Rollup2 EndProd-Code
--------- ----------------- ------- ------- ------------
P100      Potatoes          P2         P3   P100
P200      Potatoes GS       P4         P5   P200
P300      Potatoes GSS      P1         P6   P100

我想要做的是创建一个查询,如果 Prod-Code = EndProd-Code 将获取行。但如果它们不同,我想用来自 EndProd-Code 行的值覆盖 Rollup1 和 Rollup2 的值

使用上述数据运行查询的示例将在下面产生。查看如何使用 P100 的汇总值覆盖 Prod-Code P300 的汇总,因为它具有该 EndProd-Code

Prod-Code Name              Rollup1 Rollup2 EndProd-Code
--------- ----------------- ------- ------- ------------
P100      Potatoes          P2      P3      P100
P200      Potatoes GS       P4      P5      P200
P300      Potatoes GSS      P2      P3      P100
4

2 回答 2

2
SELECT p.ProdCode, p.Name, CASE WHEN p.ProdCode=p.EndProdCode THEN p.Rollup1 ELSE pm.Rollup1 END [Rollup1],
       CASE WHEN p.ProdCode=p.EndProdCode THEN p.Rollup2 ELSE pm.Rollup2 END [Rollup2]
FROM ProdTable p
JOIN ProdTable pm ON (pm.ProdCode=pm.EndProdCode and p.EndProdCode=pm.EndProdCode)
ORDER BY p.ProdCode;

SQL 小提琴:http ://sqlfiddle.com/#!3/fb6b5/3

于 2013-03-01T00:15:16.500 回答
0

假设您的Prod-Code列是主键(或至少是唯一的),以下应该做得很好:

select ProdCode    = t1.ProdCode ,
       Name        = t1.Name     ,
       Rollup1     = coalesce( t2.Rollup1 , t1.Rollup1 ) ,
       Rollup2     = coalesce9 t2.Rollup2 , t2.Rollup2 ) ,
       EndProdCode =  t1.EndProdCode
from      myTable t1
left join myTable t2 on t2.ProdCode  = t1.EndProdCode
                    and t2.ProdCode != t1.ProdCode
于 2013-03-01T00:44:24.410 回答