我想拉除 Oracle SQL 中的最后一行之外的所有行
我的数据库是这样的
Prikey - Auto_increment
common - varchar
miles - int
所以我想总结除按公共分组的主键排序的最后一行之外的所有行。这意味着对于每个不同的共同点,里程将被相加(最后一个除外)
注意:发布此答案后,问题已更改。前两个查询适用于原始问题。最后一个查询(在附录中)适用于更新的问题。
这应该可以解决问题,尽管对于较大的表会有点慢:
SELECT prikey, authnum FROM myTable
WHERE prikey <> (SELECT MAX(prikey) FROM myTable)
ORDER BY prikey
此查询更长,但对于大型表,它应该更快。我将由您决定:
SELECT * FROM (
SELECT
prikey,
authnum,
ROW_NUMBER() OVER (ORDER BY prikey DESC) AS RowRank
FROM myTable)
WHERE RowRank <> 1
ORDER BY prikey
附录问题有更新;这是更新的答案。
SELECT
common,
SUM(miles)
FROM (
SELECT
common,
miles,
ROW_NUMBER() OVER (PARTITION BY common ORDER BY prikey DESC) AS RowRank
FROM myTable
)
WHERE RowRank <> 1
GROUP BY common
查询以检索表中除第一行和最后一行之外的所有记录
select * from table_name
where primary_id_column not in
(
select top 1 * from table_name order by primary_id_column asc
)
and
primary_id_column not in
(
select top 1 * from table_name order by primary_id_column desc
)
看起来我有点太晚了,但这是我的贡献,类似于 Ed Gibbs 的第一个解决方案,但不是计算表中每个值的最大 id,然后使用内联视图进行比较。
选择 d1.prikey, d1.authnum 从 myTable d1, (SELECT MAX(prikey) prikey myTable FROM myTable) d2 哪里 d1.prikey != d2.prikey
至少我认为如果您想不使用分析,这会更有效。