算在SQL查询问题中

时间:2017-10-26 07:11:05

标签: mysql sql count

只想从订单表中选择2条最新记录,其中AGENT_CODE的数量小于3,

指导我以有效的方式执行此操作,我不希望在此查询运行时查看所有记录。

我的SQL查询是这样的,但不起作用

SELECT ORD_NUM, ORD_DATE
FROM ORDERS
WHERE ADVANCE_AMOUNT>50
AND ( SELECT ORD_DATE, COUNT( AGENT_CODE )
    FROM ORDERS
    HAVING COUNT( AGENT_CODE ) < 3
    ORDER BY ORD_DATE DESC LIMIT 5;)
ORDER BY ORD_DATE DESC LIMIT 2;

我的ORDERS表是

CREATE TABLE `orders` (
  `ORD_NUM` int(11) NOT NULL,
  `ADVANCE_AMOUNT` int(11) NOT NULL,
  `ORD_DATE` date NOT NULL,
  `CUST_CODE` varchar(10) NOT NULL,
  `AGENT_CODE` varchar(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


INSERT INTO `orders` (`ORD_NUM`, `ADVANCE_AMOUNT`, `ORD_DATE`, `CUST_CODE`, `AGENT_CODE`) VALUES
(1, 3500, '2017-08-15', 'C00002', 'A08'),
(2, 2500, '2017-09-16', 'C00003', 'A08'),
(3, 500, '2017-07-20', 'C00023', 'A08'),
(4, 4000, '2017-09-16', 'C00007', 'A10'),
(5, 1500, '2017-09-23', 'C00008', 'A04'),
(6, 2500, '2017-07-30', 'C00025', 'A10'),
(7, 4000, '2017-02-15', 'C00008', 'A11'),
(8, 1500, '2017-05-15', 'C00021', 'A11'),
(9, 2500, '2017-12-18', 'C00025', 'A11');

我的目的是选择这些

   ORD_NUM ORD_DATE
---------- ---------
       5   2017-09-23
       4   2017-09-16

4 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT ORD_NUM, ORD_DATE
FROM ORDERS
WHERE ADVANCE_AMOUNT>50
group by ord_num, ord_date
having count(agent_code)<3
ORDER BY ORD_DATE DESC LIMIT 2;

修改 对不起,试试这个:

SELECT ORD_NUM, ORD_DATE
FROM ORDERS as a
WHERE ADVANCE_AMOUNT>50
and (select count(agent_code)
     from orders as b
     where a.agent_code=b.agent_code)<3
ORDER BY ORD_DATE DESC LIMIT 2;

答案 1 :(得分:1)

加入一个子查询,该子查询获取计数小于3的代理程序代码:

SELECT ORD_NUM, ORD_DATE
FROM ORDERS AS o
JOIN (SELECT agent_code
      FROM orders
      GROUP BY agent_code
      HAVING COUNT(*) < 3) AS a
ON o.agent_code = a.agent_code
WHERE ADVANCE_AMOUNT>50
ORDER BY ORD_DATE DESC
LIMIT 2

DEMO

答案 2 :(得分:0)

请记住,在AND运算符之后放置的任何内容都必须是布尔值:

.relative:hover

如果您不想在运行此查询时遍历所有记录,请使用包含与条件匹配的条目的辅助表

AND (whatever condition with true/false value)

只要对原始表进行插入值,就使用触发器更新此aux表。 https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

答案 3 :(得分:-1)

WITH CTE AS

(  
    SELECT *
    FROM ORDERS
    WHERE ADVANCE_AMOUNT>50
)

SELECT ORD_NUM, ORD_DATE FROM CTE
GROUP BY AGENT_CODE
HAVING COUNT(*) < 3
ORDER BY ORD_DATE DESC LIMIT 2;