Max(datetime)忽略秒

时间:2016-10-28 09:14:50

标签: sql-server datetime group-by max

我的sql查询工作正常但是当我找到相同小时和分钟的日期时,我无法使查询生效。例如: enter image description here

在列" trans_date"我无法使用我的查询,因为使用max(trans_date)我没有得到任何结果,不知何故sql忽略秒。

这是我完整的SQL句子:

SELECT till.code,art.description
FROM [TCPOS4].[dbo].[transactions] as tra,
TCPOS4.dbo.articles as art,[TCPOS4].[dbo].[trans_articles] as tro,
[TCPOS4].[dbo].[tills] as till,[TCPOS4].[dbo].[shops] as shop 
where tra.till_id=till.id and shop.id=till.shop_id and tro.transaction_id=tra.id and  
art.id=tro.article_id  and tra.trans_date =(select max(trans_date) 
from tcpos4.dbo.transactions as t2 where t2.till_id=tra.till_id  and  trans_date  > '2016-10-26 00:00:0.000' and trans_date< '2016-10-27 00:00:00.000' )
group by till.code,art.description 

通过这个查询我得到的每个&#34;代码&#34;从2016-10-26到2016-10-27最大的transaction_date,但我没有从代码&#34; 5446&#34;获得任何信息。我应该得到&#34; TABLE CHOCOLECHE-CONGUITOS&#34;因为它是范围内的最大trans_date。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用与以下不同的方法吗?

SELECT code, description
 FROM
 (
  SELECT till.code, art.description,
    row_number() OVER (PARTITION BY till.code ORDER BY trans_date DESC) RowNum
   FROM [TCPOS4].[dbo].[transactions] AS tra
   LEFT JOIN [TCPOS4].[dbo].[tills] AS till
    ON tra.till_id=till.id
   LEFT JOIN [TCPOS4].[dbo].[shops] AS shop
    ON shop.id=till.shop_id
   LEFT JOIN [TCPOS4].[dbo].[trans_articles] AS tro
    ON tro.transaction_id=tra.id
   LEFT JOIN TCPOS4.dbo.articles AS art
    ON art.id=tro.article_id
 ) sbt
 WHERE RowNum=1

通过这种方式,即使你有完全相同的日期,你也会得到每个till.code的一个结果。

如果需要,您可以在ORDER BY中添加更多字段。

编辑:删除了PARTITION BY中的art.description。

编辑2:使用LEFT JOIN转换

答案 1 :(得分:0)

...CAST(tra.trans_date AS DATE) = (select CAST(max(trans_date) AS DATE)...