我需要一些Select的帮助。
以下是尝试为您提供数据示例。
数量:1 |日期:2014-05-01 | ClientCode:001 |状态:P |序列: 0 |
数量:1 |日期:2014-05-01 | ClientCode:001 |状态:X |序列: 1 |
数量:2 |日期:2014-06-30 | ClientCode:005 |状态:X |序列: 0 |
数量:2 |日期:2014-06-30 | ClientCode:005 |状态:Z |序列: 1 |
数量:2 |日期:2014-06-30 | ClientCode:005 |状态:A |序列: 2 |
我需要一个Select,它给我所有记录的最高"序列"在具有相同"数字"
的那些中所需的输出将返回带有数字1 /序列1和数字2 /序列4
的行我设法使用临时表来执行此操作,但速度非常慢。
你能帮助我吗?
先谢谢
答案 0 :(得分:2)
使用ROW_NUMBER()
:
;WITH TestTable(Number, Date, ClientCode, Status, Sequence) AS(
SELECT 1, '2014-05-01', '001', 'P', 0 UNION ALL
SELECT 1, '2014-05-01', '001', 'X', 1 UNION ALL
SELECT 2, '2014-06-30', '005', 'X', 0 UNION ALL
SELECT 2, '2014-06-30', '005', 'P', 1 UNION ALL
SELECT 2, '2014-06-30', '005', 'X', 2 UNION ALL
SELECT 10, '2015-01-01', '555', 'P', 0 UNION ALL
SELECT 15, '2015-02-08', '666', 'P', 0 UNION ALL
SELECT 15, '2015-02-08', '666', 'C', 1 UNION ALL
SELECT 15, '2015-02-08', '666', 'T', 2 UNION ALL
SELECT 15, '2015-02-08', '666', 'X', 3 UNION ALL
SELECT 15, '2015-02-08', '666', 'X', 4
)
SELECT
Number,
Date,
ClientCode,
Status,
Sequence
FROM(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY Number ORDER BY Sequence DESC)
FROM TestTable
)t
WHERE RN = 1
<强> RESULT 强>
Number Date ClientCode Status Sequence
----------- ---------- ---------- ------ -----------
1 2014-05-01 001 X 1
2 2014-06-30 005 X 2
10 2015-01-01 555 P 0
15 2015-02-08 666 X 4
答案 1 :(得分:2)
SELECT *
FROM table t
WHERE NOT EXISTS ( SELECT 'a'
FROM table t2
WHERE t2.number = t.number
AND t2.sequence > t.sequence
)
答案 2 :(得分:0)
试试这个:
SELECT
Number,
Date,
ClientCode,
Status,
Max( Sequence)
FROM
TableName
Group by
ClientCode;
只需按客户端代码分组,并使用序列上的最大聚合函数来获取与最大序列代码关联的值。
答案 3 :(得分:0)
试试这个..
With x as (select number, max(sequence)from yourfile group by number)
select y.number,y.sequence,y.clientcode
from x, yourfile y
where x.number=y.number
and y.sequence=x.sequence
答案 4 :(得分:0)
使用相关子查询查找每个数字的最大序列值:
SELECT *
FROM TableName t1
where sequence = (select max(sequence) from tablename t2
where t1.number = t2.number)
如果一个数字具有两个相同的最大序列行,则返回两行。