gpt4 book ai didi

多个where子句上的SQL Oracle rownum?

转载 作者:行者123 更新时间:2023-12-04 22:31:28 27 4
gpt4 key购买 nike

select * from MYTABLE t 
where EQUIPMENT = 'KEYBOARD' and ROWNUM <= 2 or
EQUIPMENT = 'MOUSE' and ROWNUM <= 2 or
EQUIPMENT = 'MONITOR' and ROWNUM <= 2;

我正在尝试运行一个查询,该查询在字段(即设备)上返回匹配项,并将每种设备类型的输出限制为 2 条记录或更少。我知道这可能不是使用多个 where 子句的最佳方法,但是我过去曾使用过由 or 语句分隔,但不适用于 rownum。似乎它只返回最后一个 where 语句。提前致谢..

最佳答案

WITH numbered_equipment AS (
SELECT t.*,
ROW_NUMBER() OVER( PARTITION BY EQUIPMENT ORDER BY NULL ) AS row_num
FROM MYTABLE t
WHERE EQUIPMENT IN ( 'KEYBOARD', 'MOUSE', 'MONITOR' )
)
SELECT *
FROM numbered_equipment
WHERE row_num <= 2;

SQLFIDDLE

如果要根据其他列确定选择哪些行的优先级,请修改查询的 ORDER BY NULL 部分,将优先级最高的元素放在首位。

编辑

要拔出设备匹配且状态为事件的行,请使用:
WITH numbered_equipment AS (
SELECT t.*,
ROW_NUMBER() OVER( PARTITION BY EQUIPMENT ORDER BY NULL ) AS row_num
FROM MYTABLE t
WHERE EQUIPMENT IN ( 'KEYBOARD', 'MOUSE', 'MONITOR' )
AND STATUS = 'Active'
)
SELECT *
FROM numbered_equipment
WHERE row_num <= 2;

SQLFIDDLE

关于多个where子句上的SQL Oracle rownum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20981913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com