【问题标题】:How to get data order by Sort Value如何按排序值获取数据顺序
【发布时间】:2019-07-27 10:47:55
【问题描述】:

我有三个名为 ServiceLocationSeriveLocation 的表。

Service表数据如下

ServiceID       Service     SortValue
1           Customer call       5
2               Reload          2
3           Internet setting    3
4               E care          7
5               Anti call       4
6               MMS             1
7            settings           6

SeriveLocation表数据如下

FkLcoationID    FkServiceID   SortValue
001                 1           2
002                 1           1
003                 1           2
004                 1           NULL
005                 1           4
001                 2           3
002                 2           4
003                 2           4
004                 2           NULL
005                 2           1
001                 3           4
002                 3           2
003                 3           3
004                 3           NULL
005                 3           3
001                 4           1
002                 4           3
003                 4           1
004                 4           NULL
005                 4           2

现在我需要通过SeriveLocation 表的sortValue 获取其services 和serviceIDs 的特定位置数据。如果SeriveLocation 的表sortValueNULL 我需要使用Service 表的SortValue 获得服务订单

我的预期输出是locationId = 001

LocationId = 004时(根据映射表,位置004没有sortVlaue,所以它的排序顺序需要取自服务表)

我该怎么做?

我试过这个,当 Sortvalue 为 Null 时

select sm.FkBranchId,sm.FkServiceId,s.ServiceName from SeriveLocation sm
INNER JOIN Service s ON s.ServiceID = sm.FkServiceId
where sm.FkLocationId = 004 
order by s.SortValue 

【问题讨论】:

  • 到目前为止你尝试过什么?看起来您只需要一个 JOIN 和一个 ORDER BY 子句。
  • @Larnu 我是新来的先生,你能帮帮我吗
  • 查看JOINORDER BY 的语法。最好的学习方法是研究和尝试; JOIN 是 SQL 的基础,因此您需要了解它们。如果您失败了,请编辑您的尝试,以便我们解释您出错的地方。

标签: sql sql-server join sql-order-by


【解决方案1】:

我想你想要left joincoalesce()

select s.Service, sl.ServiceId,
       coalesce(sl.SortValue, s.SortValue)
from ServiceLocation sl left join
     Service s
     on sl.ServiceId = s.ServiceId
where sl.FkLocationId  = ?
order by coalesce(sl.SortValue, s.SortValue);

【讨论】:

  • 在 coalesce 里面会发生什么?当 SeriveLocation 表排序值为空时..是否从服务表中获取排序顺序?我是对的
  • 我应该在哪里添加 where 条件?例如FkLocationId = 004 ??
  • @亚当。 . . COALESCE() 返回第一个非NULL 值。
猜你喜欢
  • 2021-09-10
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 2020-02-16
  • 2020-11-26
相关资源
最近更新 更多