我正在尝试使用两个日期之间的uniq序列号获取所有记录。但我无法写出正确的sql。
这是我当前的SQL查询和结果。共有3条记录,带有两个XYZABC1230序列号。
select * from t_recorded_test
where office_id = '1710011001123'
and record_date > '2017-11-01'
and record_date < '2017-12-08'
and test_result = 'true';
MODEM_MODEL MODEM_SERIAL_NUMBER OFFICE_ID RECORD_DATE RECORD_ID TEST_RESULT
Type2ModelB XYZABC1230 1710011001123 2017-11-01 19:35:54.0 ccf57f20d585424abc9bce781ada9dcc TRUE
Type2ModelB XYZABC1230 1710011001123 2017-11-01 19:33:54.0 168ce13ed9644f128f7769432ad6ba2f TRUE
Type2ModelB XYZABC12312 1710011001123 2017-12-03 19:33:54.0 ab727f836c354f159703565b9eed3331 TRUE
但我希望只有两个记录XYZABC1230和XYZABC12312。我该怎么办?
编辑:
对于所有相同的序列号,我只需要一个结果。日期并不重要,但我必须将其用于限制。
答案 0 :(得分:1)
--This is for MSSQL Server
with CTE as(
select *,(row_number() over (partition by MODEM_SERIAL_NUMBER order by MODEM_SERIAL_NUMBER)) 'ROW_N' from T_RECORDED_TEST
where OFFICE_ID='1710011001123' and RECORD_DATE > '2017-11-01' and RECORD_DATE < '2017-12-08' and TEST_RESULT = 'TRUE')
select MODEM_MODEL,MODEM_SERIAL_NUMBER,OFFICE_ID,RECORD_DATE,RECORD_ID,TEST_RESULT from CTE where ROW_N=1
答案 1 :(得分:0)
使用GROUP BY函数和MAX(ROWID)
,假设您希望组中的最新行按值。
SELECT * FROM T_RECORDED_TEST
WHERE ROWID IN (
SELECT MAX(ROWID)
FROM T_RECORDED_TEST
where office_id='1710011001123'
and record_date > '2017-11-01'
and record_date < '2017-12-08'
and test_result = 'true'
GROUP BY MODEM_SERIAL_NUMBER;
)
答案 2 :(得分:0)
*是罪魁祸首。如果您只对MODEM_SERIAL_NUMBER感兴趣,可以使用如下的distinct。
SELECT DISTINCT
( modem_serial_number )
FROM
t_recorded_test
WHERE
office_id = '1710011001123'
AND record_date > '2017-11-01'
AND record_date < '2017-12-08'
AND test_result = 'true';