查询和返回关系的最佳方法是什么?

时间:2019-03-17 10:51:50

标签: sql

我对SQL还是很陌生,喜欢如何解决以下问题。预先感谢!

我有一个包含2列的表格,OldProductLineID及其各自的NewProductLineID。

如何返回带有1个附加列(第3列)的表以显示ProductLineID之间的关系

样本数据

OldID | NewID  
123   | 987  
234   | 987  
456   | 876  
456   | 877  
567   | 777

我需要的结果

OldID | NewID | Relationship    
123   | 987   | Regroup  
234   | 987   | Regroup  
456   | 876   | Split  
456   | 877   | Split  
567   | 777   | Rebrand   

在上述情况下,
1)将OldID 123和234重新组合为NewID987。
2)将OldID 456拆分为NewID 876和877。
3)OldID 567被更名为NewID 777

再次感谢!

2 个答案:

答案 0 :(得分:2)

您可以像下面这样使用COUNT() OVER PARTITION BY。它应该适用于大多数数据库。

SELECT oldid, 
       newid, 
       CASE 
         WHEN s = 1 
              AND r > 1 THEN 'Regroup' 
         WHEN r = 1 
              AND s > 1 THEN 'Split' 
         WHEN r = 1 
              AND s = 1 THEN 'Rebrand' 
         ELSE 'Wrong Data(Mix)' 
       END AS 'Relationship' 
FROM   (SELECT *, 
               Count(*) OVER(partition BY oldid) s, 
               Count(*) OVER(partition BY newid) r 
        FROM   [yourtablename]) t 
ORDER  BY oldid 

我已经在SQL Server中创建了一个示例,您可以在这里Online Demo in SQL Server

进行检查

输出

+-------+-------+--------------+
| OldId | NewId | Relationship |
+-------+-------+--------------+
| 123   | 987   | Regroup      |
+-------+-------+--------------+
| 234   | 987   | Regroup      |
+-------+-------+--------------+
| 456   | 876   | Split        |
+-------+-------+--------------+
| 456   | 877   | Split        |
+-------+-------+--------------+
| 567   | 777   | Rebrand      |
+-------+-------+--------------+

答案 1 :(得分:0)

这只是猜测您的要求,无论您使用的是哪种dbms,它都可以工作:

select 
  t.OldID, t.NewID,
  case
    when exists (
      select 1 from tablename
      where newid = t.newid and oldid <> t.oldid
    ) then 'Regroup' 
    when exists (
      select 1 from tablename
      where newid <> t.newid and oldid = t.oldid
    ) then 'Split'
    else 'Rebrand'
  end Relationship
from tablename t

请参见demo

相关问题