【问题标题】:Assign unique ID's to three tables in SELECT query, ID's should not overlap在 SELECT 查询中为三个表分配唯一 ID,ID 不应重叠
【发布时间】:2015-06-20 17:02:33
【问题描述】:

我正在开发 SQL Sever,我想为从这三个表中提取的行分配唯一的 ID,但 ID 不应重叠。

假设,表一包含汽车数据,表二包含房屋数据,表三包含城市数据。我想将所有这些数据提取到一个具有唯一 ID 的表中,每个人都说汽车从 1 到 100,房子从 101 到 200,城市从 300 到 400。

如何仅使用选择查询来实现此目的。我不能使用插入语句。

更准确地说, 我有一张表,其中包含 500-700 的计算机系统/服务器主机信息。 我还有另一个表、存储设备(ID 为 200-600)和路由器(ID 为 700-900)。我已经收集了系统数据。现在我想以这样一种方式提取存储系统和路由器数据,即我端的合并数据应该具有所有记录的唯一 ID。这只需要通过使用 SELECT 查询来完成。

我使用 SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS UniqueID 并将其存储在临时表中(存储和路由器分开)。但我相信这可能会导致一些重叠。请建议任何其他方式来做到这一点。

 An extension to this question:

Creating consistent integer from a string: 

All I have is various strings like this  
 String1
 String2Hello123 
 String3HelloHowAreYou             


I Need to convert them in to positive integers say some thing like     
String1 = 12 
String2Hello123 = 25 
String3HelloHowAreYou = 4567


Note that I am not expecting the numbers in any order.Only requirement is number generated for one string should not conflict with other

Now later after the reboot If I do not have 2nd string instead there is a new string

        String1 = 12    
        String3HelloHowAreYou = 4567    
        String2Hello123HowAreyou = 28    

Not that the number 25 generated for 2nd string earlier can not be sued for the new string.

Using extra storage (temp tables) is not allowed

【问题讨论】:

  • 您能否展示这些表中的一些示例数据,以及选择查询的预期输出?
  • 更准确地说,我有一张表,其中包含计算机系统/服务器主机信息,其 id 为 500-700。我还有另一个表、存储设备(ID 为 200-600)和路由器(ID 为 700-900)。我已经收集了系统数据。现在我想以这样一种方式提取存储系统和路由器数据,即我端的合并数据应该具有所有记录的唯一 ID。这只需要通过使用 SELECT 查询来完成。我正在使用 SELECT ABS(CAST(CAST(NEWID() AS VARBINARY) AS INT)) AS UniqueID 并将其存储在临时表中(存储和路由器分开)。

标签: sql sql-server oracle oracle-sqldeveloper


【解决方案1】:

如果您不在乎数据来自哪里:

with dat as (
select 't1' src, id from table1 
union all 
select 't2' src, id  from table2
union all 
select 't3' src, id  from table3
)
select *
     , id2 = row_number() over( order by _some_column_ )
from dat

【讨论】:

  • 请注意,如果 3 个表具有相同数量的列并且结构相同,这将起作用,否则 UNION 将失败。
  • @A ツ 我知道,我只是在谈论您的 WITH 表表达式中的 UNION 查询
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多