Sql server 如何从SQL上的组中检索最大值日期
有人能给我推荐一个SQL查询吗?我正在与之斗争 我有两张桌子: 表1:Sql server 如何从SQL上的组中检索最大值日期,sql-server,Sql Server,有人能给我推荐一个SQL查询吗?我正在与之斗争 我有两张桌子: 表1:pos\u-tran,其模式如下: pos_tran ( entry_no CHAR 8 (NOT NULL PK), barcode CHAR 8, tran_amt NUMERIC 9, tran_qty NUMERIC 9, des CHAR 20 ) 表2:pos\u-tran\u-hd和模式: pos_tran_hd ( entry_no CHAR 8 (NOT NULL PK), Location_id CH
pos\u-tran
,其模式如下:
pos_tran
(
entry_no CHAR 8 (NOT NULL PK),
barcode CHAR 8,
tran_amt NUMERIC 9,
tran_qty NUMERIC 9,
des CHAR 20
)
表2:pos\u-tran\u-hd
和模式:
pos_tran_hd
(
entry_no CHAR 8 (NOT NULL PK),
Location_id CHAR 3,
entry_date DATETIME8,
)
现在,我想在使用entry\u no
连接两个表之后对条形码进行分组,并在我写这篇文章时从列表中检索max(last date)
条目,如果有人更强调我的话
SELECT pthd.maxed, pt.barcode, tran_amt, tran_qty from pos_tran pt,
(
SELECT entry_no, max(entry_date) maxed
FROM
pos_tran_hd
where location_id=015 GROUP BY entry_no
)
pthd
WHERE pthd.entry_no=pt.entry_no
ORDER BY barcode,pthd.maxed
但这并不是我想要的那样,在没有给出最长日期的情况下给了我大约200000张唱片,这样:
2014-06-23 00:00:00.000 21155192 28000.000 7.00
2014-07-01 00:00:00.000 21155192 4000.000 1.00
2014-07-08 00:00:00.000 21155192 8000.000 2.00
2014-07-12 00:00:00.000 21155192 12000.000 3.00
2014-08-13 00:00:00.000 21155192 4000.000 1.00
2014-09-16 00:00:00.000 21155192 12000.000 3.00
2014-10-06 00:00:00.000 21155192 12000.000 3.00
2015-01-26 00:00:00.000 21155192 12000.000 3.00
2015-05-29 00:00:00.000 21155192 4000.000 1.00
2018-01-05 00:00:00.000 21155192 28000.000 4.00
但实际上它应该给我最后一条记录,它有max(输入日期)
,而数据库中最糟糕的部分是我正在使用mssql2000
如果有人有积极的建议,请帮助我。谢谢。您的第二个查询通过
entry\u no
选择一个maxentry\u date
,而每个entry\u no
只有一个entry\u date
。在你的描述中,你说的是“按条形码分组”。。。但当按条形码进行分组(每个条形码只显示一行)时,不能显示每个条目的金额和数量
那么,让我们从这个开始:
select pt.barcode, max(pthd.entry_date) maxed
from pos_tran pt
inner join pos_tran_hd pthd on pt.entry_no = pthd.entry_no
group by pt.barcode
order by pt.barcode
然后,要显示最后一个输入日期每条码的完整行,并且由于您仍在使用SQL Server 2000,我们需要一个子查询来计算每条码的最大值,就像我以前做的那样,并将这些值与我们要显示的值进行比较:
SELECT pthd.entry_date maxed, pt.barcode, pt.tran_amt, pt.tran_qty
FROM pos_tran pt
INNER JOIN pos_tran_hd pthd ON pt.entry_no = pthd.entry_no
WHERE EXISTS (
select pt2.barcode
from pos_tran pt2
inner join pos_tran_hd pthd2 on pt2.entry_no = pthd2.entry_no
group by pt2.barcode
having pt2.barcode = pt.barcode AND max(pthd2.entry_date) = pthd.entry_date)
ORDER BY pt.barcode
您需要max()
函数从pos\u tran\u hd获取最大日期,然后将其加入并获取其余字段,然后将其加入pos\u tran以获取相应的最大日期结果
pthd.maxed,pt.barcode,交易金额,交易数量
select t.maxed,ps.barcode,ps.tran_amt,ps.tran_qty from
(SELECT pd.*
from pos_tran_hd pd
inner join
(
SELECT max(entry_date) maxed
FROM
pos_tran_hd
)
pthd
on pthd.maxed=pos_tran_hd.entry_date
) as t inner join pos_tran ps on t.entry_no =ps.entry_no
您的预期结果是什么?您的问题说您正在使用“MySQL 2000”,但标签是针对SQL Server的-现在是哪个??请修复标记以反映mysql
,或者更改问题以包含您真正使用的内容!应该是2018-01-05,这在上述组别中较高。你的问题毫无意义,要按第二个表中的entry\u no
分组,你需要在entry\u no
中有多个相同值的记录才能生效。正如你所说,它是主键,所以它是唯一的!因此,按它分组不会有任何作用。非常感谢您,先生。。。我认为这是今天最好的答案,它的效果非常好。