SQL序列号和开始/结束日期分析

时间:2018-02-13 15:12:31

标签: sql sql-server

我是SQL的新手(SQL Management Studio 2016),今天早上我才加入该网站...所以我的第一篇文章!我一直在寻找关于我的问题的网站解决方案。我找到了一些链接,但没有(我认为)会尝试一些。我有一个包含锅炉服务数据的表。一个地址可以有多个日期/序列号。我期待创建一个脚本,证明最新的序列号开始日期小于或等于最新的顺序结束日期。所以,在我的例子中,我想为start_date字段选择MAX seq_no,为end_date字段选择第二个MAX seq_no,以确保它们没有超过时间刻度。

我的样本数据已添加为图像(希望!)......只有两个地址,但实际上有1000个地址):

我已经尝试过SLQ,最初只获得最终日期的最大seq_no,但它只是不断带回所有条目:

select max (seq_no) as SEQNO, end_date, cmpnt_ref, prty_id
FROM hgmpcych
where prty_id in ('ABBEY10_TD12','ABBEY12_TD12') and  cmpnt_ref='Boiler' and cycle_no='5'
group by end_date,prty_id,cmpnt_ref,seq_no
order by prty_id

这可能是非常基本的,但我仍然是SQL的新手。任何提示,建议或提示都将非常感激。

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER()标记每个组中的行,并仅选择标有1或2的行(两个“最新”行)......

WITH
  enumerated_hgmpcych AS
(
  SELECT
    seq_no, start_date, end_date, cmpnt_ref, prty_id,
    ROW_NUMBER() OVER (PARTITION BY prty_id, cmpnt_ref
                           ORDER BY seq_no DESC
                      )
                        desc_seq_enumerator
  FROM
    hgmpcych
  WHERE
        prty_id in ('ABBEY10_TD12','ABBEY12_TD12')
    AND cmpnt_ref='Boiler'
    AND cycle_no='5'
)
SELECT
  *
FROM
  enumerated_hgmpcych
WHERE
  desc_seq_enumerator <= 2
ORDER BY
  prty_id,
  cmpnt_ref,
  seq_no

如果您愿意,可以将其折叠为每组一行......

WITH
  enumerated_hgmpcych AS
(
  SELECT
    seq_no, start_date, end_date, cmpnt_ref, prty_id,
    ROW_NUMBER() OVER (PARTITION BY prty_id, cmpnt_ref
                           ORDER BY seq_no DESC
                      )
                        desc_seq_enumerator
  FROM
    hgmpcych
  WHERE
        prty_id in ('ABBEY10_TD12','ABBEY12_TD12')
    AND cmpnt_ref='Boiler'
    AND cycle_no='5'
)
SELECT
  prty_id,
  cmpnt_ref,
  MAX(CASE WHEN desc_seq_enumerator = 1 THEN seq_no     END)   AS final_seq_no,
  MAX(CASE WHEN desc_seq_enumerator = 1 THEN start_date END)   AS final_start_date,
  MAX(CASE WHEN desc_seq_enumerator = 1 THEN end_date   END)   AS final_end_date,
  MAX(CASE WHEN desc_seq_enumerator = 2 THEN seq_no     END)   AS prev_seq_no,
  MAX(CASE WHEN desc_seq_enumerator = 2 THEN start_date END)   AS prev_start_date,
  MAX(CASE WHEN desc_seq_enumerator = 2 THEN end_date   END)   AS prev_end_date
FROM
  enumerated_hgmpcych
WHERE
  desc_seq_enumerator <= 2
GROUP BY
  prty_id,
  cmpnt_ref
ORDER BY
  prty_id,
  cmpnt_ref

答案 1 :(得分:0)

如果您有max(seq_no),那么您不希望它出现在group by中:

select max (seq_no) as SEQNO, end_date, cmpnt_ref, prty_id
from hgmpcych
where prty_id in ('ABBEY10_TD12', 'ABBEY12_TD12') and
      cmpnt_ref = 'Boiler' and cycle_no = '5'
group by end_date, prty_id, cmpnt_ref
order by prty_id;