适合此SQL的样式

时间:2016-02-17 18:00:15

标签: sql coding-style

这个sql代码的新行和缩进是什么?

sql = "select p.diff, away_score - home_score, clock from 
     (select possession,away_score,home_score, play_type, clock, 
               (lag(clock, 1) over (order by id) - clock) as diff 
               from plays where game_id in #{ids}
               and league = 1 offset 1) 
       as p 
       where possession= 0 and 
       play_type not in (150, 151, 152, 153, 154, 105, 106)
       and diff > 0 and diff < 30;"

1 个答案:

答案 0 :(得分:3)

这个问题没有正确的答案。风格,格式,空白,都是个人喜好。如果它只是一行,那么SQL会非常小心(请注意,这是基于我对MS SQL Server的经验,其他系统可能有点麻烦)。如果N人查看了并且回复了这个问题,那么你会得到N个答案,而N(N-1)个反对意见。

话虽如此,以下是我的表现:

sql = "
select
   p.diff
  ,away_score - home_score
  ,clock
 from (--  Comment describing the subquery
       select
          possession
         ,away_score
         ,home_score
         ,play_type
         ,clock
         ,(lag(clock, 1) over (order by id) - clock) as diff 
        from plays
        where game_id in #{ids}
         and league = 1 offset 1
      ) as p 
  where possession = 0
   and play_type not in (150, 151, 152, 153, 154, 105, 106)
   and diff > 0
   and diff < 30;
"