簡體   English   中英

選擇最大日期,即使它為空?

[英]Select max date even if it's null?

我在表格中選擇價格到期的最高日期時遇到問題。 該表存儲歷史數據,如果上周未設置日期,它將搜索MAX日期以自動填充價格到期。

我的問題是,如果我將價格過期更新為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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM