gpt4 book ai didi

mysql - 选择最大日期,即使它为空?

转载 作者:行者123 更新时间:2023-11-30 00:09:06 26 4
gpt4 key购买 nike

我在选择表中价格到期的最大日期时遇到问题。该表存储历史数据,如果上周没有设置日期,它将搜索最大日期以自动填充价格到期时间。

我的问题是,如果我将价格到期日期更新为 NULL(有时价格不会到期),那么当我检查获取最后一个价格到期日期时,我会不断获取 NULL 条目之前的日期。我想要的是 NULL 日期(如果这是最新的条目)。

这是我的表格:

CREATE TABLE IF NOT EXISTS `customers_view_items` (
`cid` bigint(20) NOT NULL AUTO_INCREMENT,
`item` varchar(15) NOT NULL COMMENT 'item number from dProduce',
`custno` varchar(6) NOT NULL COMMENT 'customer number from dProduce',
`week_of` date NOT NULL COMMENT 'week for pricing this was saved as',
`cost` double(12,4) NOT NULL COMMENT 'current cost when this was saved',
`market_price` double(12,4) NOT NULL COMMENT 'current market price when this was saved',
`discount` double(12,4) NOT NULL COMMENT 'discount that was applied to get the price for history',
`current_margin` double(12,4) NOT NULL COMMENT 'current margin for history',
`avg_margin` double(12,4) NOT NULL COMMENT 'average margin for history',
`volume` double(12,3) NOT NULL COMMENT 'volume',
`price` double(12,4) NOT NULL COMMENT 'Price set for customer item',
`priceexp` date DEFAULT NULL COMMENT 'Date price expires',
`saved_on` datetime NOT NULL COMMENT 'Datetime of save',
`saved_by` int(11) NOT NULL COMMENT 'user id that saved',
PRIMARY KEY (`cid`),
UNIQUE KEY `custno_item_weekof` (`custno`,`item`,`week_of`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores the customer items data from customer view items sect' AUTO_INCREMENT=629 ;

到目前为止我的查询是:

SELECT 
custno,
item,
price,
UNIX_TIMESTAMP(priceexp) as priceexp
FROM `customers_view_items`
WHERE custno = 'LASP'
ORDER BY `week_of` DESC

这为我提供了数据行,但我似乎无法仅获取最新条目。

如果我执行MAX(priceexp),我只会获得最高价格到期时间(如预期)

我认为我需要执行子查询才能获得我需要的结果,但我现在迷失了。

我添加了 cid 来标识最新条目,但我认为 week_of 也可以工作(实际上是首选)

任何朝着正确方向的插入都会有很大帮助。

谢谢

最佳答案

是的。您可以使用子查询先拉取最新的记录。

select a.custno, a.item, a.price, unix_timestamp(a.priceexp) priceexp
from customers_view_items a
join (
select custno, item, max(week_of) week_of
from customers_view_items
group by custno, item) b on a.custno = b.custno and a.item = b.item and a.week_of = b.week_of;

关于mysql - 选择最大日期,即使它为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234465/

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