[英]MySQL Query: List of Part Numbers, Return Only Part Numbers Not in Database
[英]SQL Query to return a list of account numbers that have only ordered before (x) date
如果很简单,请提前道歉,但是我是SQL新手
我需要帮助为包含AccountCodes和OrderDates列表的数据库建立查询。 该数据库中包含所有已完成的订单。
我可以生成一个查询,该查询将为我提供2015年之前订购的所有物品,但是它将忽略是否在之后订购的所有物品。 同样,这给了我重复的帐户代码,这无济于事,因为我需要在以后使用此列表执行其他功能。
我要寻找的是一个查询,该查询将提供我上次订购的2015年1月1日之前的任何帐号,而不会重复任何帐号。
提前致谢
总体思路是:
select whatever
from wherever
where some conditions are met
and not exists
(
subquery to identify the records after x date
)
第一部分是您说的已经拥有的内容。
编辑从这里开始
以上内容将满足您问题中only before x date
的only before x date
部分。 关于重复的帐户代码,此查询中可能会或可能不会,这取决于需要其他哪些字段。 但是,有多种方法可以创建不同的列表。 它取决于许多事情,您的问题中没有任何事情。
SELECT DISTINCT
AccountCodes,
OrderDates
FROM
`table`
WHERE
(OrderDates <= '2015-01-01') AND OrderDates NOT IN(
SELECT
AccountCodes,
OrderDates
FROM
'table'
WHERE
OrderDates > '2015-01-01'
)
假设您的订单表中有一个auto_increment ID,则可以使用子查询仅选择您感兴趣的max子句
MariaDB [sandbox]> select aw.salesorderid,aw.customerid, aw.orderdate
-> from awsalesorderheader aw
-> where aw.customerid in (11001,11002,12368);
+--------------+------------+---------------------+
| salesorderid | customerid | orderdate |
+--------------+------------+---------------------+
| 43767 | 11001 | 2005-07-18 00:00:00 |
| 51493 | 11001 | 2007-07-20 00:00:00 |
| 72773 | 11001 | 2008-06-12 00:00:00 |
| 43736 | 11002 | 2005-07-10 00:00:00 |
| 51238 | 11002 | 2007-07-04 00:00:00 |
| 53237 | 11002 | 2007-08-27 00:00:00 |
| 71664 | 12368 | 2008-05-30 00:00:00 |
+--------------+------------+---------------------+
7 rows in set (0.00 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> select aw.salesorderid,aw.customerid, aw.orderdate
-> from awsalesorderheader aw
-> where salesorderid = (select max(aw1.salesorderid) from awsalesorderheader aw1 where aw1.CustomerID = aw.customerid
-> and aw1.orderdate < '2008-01-01' and aw.customerid in (11001,11002,12368))
-> order by aw.customerid;
+--------------+------------+---------------------+
| salesorderid | customerid | orderdate |
+--------------+------------+---------------------+
| 51493 | 11001 | 2007-07-20 00:00:00 |
| 53237 | 11002 | 2007-08-27 00:00:00 |
+--------------+------------+---------------------+
2 rows in set (0.19 sec)
如果没有auto_increment id,则可以在where和子查询中用orderdate替换id,但可能需要向select添加一个不同的子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.