Oracle - 在 SELECT 语句中使用变量

Oracle - Using variables in SELECT statement

我在SQL的背景是SQL服务器,所以请原谅我以类似的方式使用Oracle。我需要使用一个变量,这样我就可以使用存储在其中的值来执行单独的 SELECT 查询。我的目标是找到一个百分比值,该变量将保存 table.

的总值
DECLARE
  v_Count INT;

BEGIN

--get total rows
SELECT COUNT(OrderID)
INTO v_Count
FROM OrderedEquipment;

--find percentage of equipment ordered
SELECT a.Equip_Name, COUNT(b.EquipmentID), ((COUNT(b.EquipmentID)*1.0)/(v_Count*1.0)*100)
FROM Equipment a
LEFT OUTER JOIN OrderedEquipment b ON a.EquipmentID = b.EquipmentID
GROUP BY a.Equip_Name;

END;

SQL 开发人员将抛出此错误:

Error report -
ORA-06550: line 10, column 1:
PLS-00428: an INTO clause is expected in this SELECT statement

我试图寻找解决方案,并偶然发现了这个 post:

How do I use variables in Oracle SQL Developer?

但是 none 的答案确实解决了我的问题。我尝试使用 bind 变量示例,但没有用。

最简单的方法就是完全不使用变量

SELECT a.Equip_Name, COUNT(b.EquipmentID), 
    (COUNT(b.EquipmentID)*1.0)/((SELECT COUNT(OrderID) cnt FROM OrderedEquipment)*1.0)*100
  FROM Equipment a
  LEFT OUTER JOIN OrderedEquipment b ON a.EquipmentID = b.EquipmentID
  GROUP BY a.Equip_Name;

你也可以在你的块select中将数据分成3个变量

... a.Equip_Name into v1, COUNT(b.EquipmentID) into v2,
  ((COUNT(b.EquipmentID)*1.0)/(v_Count*1.0)*100) into v3 ...

并用

列出它们
dbms_output.put_line(v1||' '||v2||' '||v3);

编辑 - 这个查询应该更快:

with counter as (select count(OrderID) cnt from OrderedEquipment)
select a.Equip_Name, count(b.EquipmentID), 
    (count(b.EquipmentID)*1.0)/(max(counter.cnt)*1.0)*100
  from Equipment a
    left join OrderedEquipment b ON a.EquipmentID = b.EquipmentID
    cross join counter
  group by a.Equip_Name;