仅返回与具有多个相关记录的子表相关的表中的1个值

时间:2018-02-12 16:51:50

标签: sql sql-server

表A包含与表B相关的ID。表B还包含与表C相关的ID。我需要弄清楚如何仅根据在外部定义的层次结构返回一个值。表格。 例如: 表A(设备)

-------------------------
| DeviceID | Device Name |
-------------------------
|___001____| Server1_____|
--------------------------
|___002____| server2_____|
--------------------------

表B(翻译表)

-------------------------
| DeviceID | Value ID    |
-------------------------
|___001____|____456______|
--------------------------
|___002____|____456______|
--------------------------
|___001____|____789______|
--------------------------
|___002____|____123______|

表C(价值表)

-------------------------
|_ValueID__|___Value_____|
-------------------------
|___123____|____LOW______|
--------------------------
|___456____|____MED______|
--------------------------
|___789____|____HIGH_____|
--------------------------

我需要的是评估表a中的每个ID,如果它具有HIGH的相关值(789)我需要带回HIGH,如果它不是,如果相关的HIGH值那么我需要检查并查看如果它与MED值相关。如果设备与HIGH值无关但与MED值相关,则返回MED。最后为LOW做同样的事情。不需要返回没有值的设备。 期望的输出

------------------------------
|___Device Name___|___COST___|
------------------------------
|___Server1_______|___HIGH___|
------------------------------
|___Server2_______|___MED____|
------------------------------

我如何正确查询此信息,尤其是如果值ID可能会更改。

2 个答案:

答案 0 :(得分:1)

select a.*,
       coalesce(
         (select C.value from C, B
           where c.Value = 'HIGH'
             and b.ValueID = c.ValueID
             and b.DeviceID = a.DeviceID),
         (select C.value from C, B
           where c.Value = 'MED'
             and b.ValueID = c.ValueID
             and b.DeviceID = a.DeviceID),
         (select C.value from C, B
           where c.Value = 'LOW'
             and b.ValueID = c.ValueID
             and b.DeviceID = a.DeviceID)
       ) Value
  from a
  where exists (select null from C,B
                  where b.ValueID = c.ValueID
                    and b.DeviceID = a.DeviceID)

coalesce将返回第一个not null值,这可能满足你的愿望。

答案 1 :(得分:0)

根据您的输入和所需输出,以下查询可能会给出所需的结果:

  select a.DeviceName, c.Value 
  from TableA a inner join TableB b 
  on a.DeviceID=b.DeviceID
  inner Join TableC c
  on b.ValueID=c.ValueID