将多个计数返回到一个查询中

时间:2016-03-13 18:46:49

标签: sql oracle

我正在尝试将计数值返回到多个列(ORDERS_1990,ORDERS_1991)但我收到错误"缺少关键字"。

SELECT
 (SELECT COUNT(*) FROM ORDERS WHERE (ODATE BETWEEN '01-JAN-90' AND '31-DEC-90')),
 (SELECT COUNT(*) FROM ORDERS WHERE (ODATE BETWEEN '01-JAN-91' AND '31-DEC-91'))
INTO ORDERS_1990, ORDERS_1991
FROM ORDERS;

2 个答案:

答案 0 :(得分:1)

您最有可能收到消息,因为您在PLSQL块之外使用SELECT ... INTO ...。如果您只想标记结果,只需正常命名子查询;

SELECT
 (SELECT COUNT(*) FROM ORDERS 
  WHERE (ODATE BETWEEN '01-JAN-90' AND '31-DEC-90')) ORDERS_1990,
 (SELECT COUNT(*) FROM ORDERS 
  WHERE (ODATE BETWEEN '01-JAN-91' AND '31-DEC-91')) ORDERS_1991
FROM DUAL;

答案 1 :(得分:0)

您可以使用条件聚合:

SELECT SUM(CASE WHEN ODATE BETWEEN '01-JAN-90' AND '31-DEC-90' THEN 1 ELSE 0 END),
       SUM(CASE WHEN ODATE BETWEEN '01-JAN-91' AND '31-DEC-91' THEN 1 ELSE 0 END)
INTO ORDERS_1991, ORDERS_1992
FROM ORDERS;

我不确定为什么你会得到一个"缺少关键字"错误。我希望错误是你返回太多行。我认为以下内容应该有效(假设您在PL / SQL块中):

SELECT (SELECT COUNT(*) FROM ORDERS WHERE (ODATE BETWEEN '01-JAN-90' AND '31-DEC-90')),
       (SELECT COUNT(*) FROM ORDERS WHERE (ODATE BETWEEN '01-JAN-91' AND '31-DEC-91'))
INTO ORDERS_1990, ORDERS_1991
FROM dual;