概要;某些列加入一些表有类似的结果。我们如何对它们进行分组并选择max(column)。
我的查询是;
SELECT DISTINCT TOP (1000) LG_070_ITEMS.CODE AS PRODCODE,
LG_070_01_SERILOTN.CODE AS CODE,
LG_070_01_SLTRANS.OUTCOST,
LG_070_01_SLTRANS.LOGICALREF AS LREF,
LG_070_01_SLTRANS.INSLTRANSREF,
LG_070_01_SLTRANS.INVENNO,
LG_070_01_SLTRANS.INTRANSREF,
LG_070_01_SLTRANS.STTRANSREF
FROM LG_070_01_SERILOTN
INNER JOIN LG_070_01_SLTRANS ON LG_070_01_SLTRANS.SLREF = LG_070_01_SERILOTN.LOGICALREF
INNER JOIN LG_070_ITEMS ON LG_070_ITEMS.LOGICALREF = LG_070_01_SERILOTN.ITEMREF
WHERE [TIGERDB].[dbo].[LG_070_01_SERILOTN].CODE = '868328002749220'
并且数据库的答案也是;
产品代码--------------- COST - LREF ------一个twho三四
K-3773 868328002749220 50,85 46255 ------- 0 10 0 33584
K-3773 868328002749220 50,85 46504 ------- 46255 10 33584 33639
K-3773 868328002749220 50,85 46524 ------- 46504 11 33639 33640
K-3773 868328002749220 50,85 51273 ------- 46524 11 33640 38581
K-3773 868328002749220 50,85 51285 ------- 51273 9 38581 38587
K-3773 868328002749220 50,85 52275 ------- 51273 11 38581 39823
K-3773 868328002749220 50,85 52276 ------- 52275 9 39823 39824
现在我的问题是,如何选择最后一行。它可以更大的LREF列或第一列。
我的查询是一样的。我使用数字,其中stuation和结果与此相同。
我尝试使用max(columname)和group by othercolumns等。 我使用查询设计器和microsoft sql server管理工具。
在那三个表中,未选中的列对我来说并不重要。使用mysql我可以使用select ... max(lref)从...加入...按代码分组,但我必须这样做MSSQL。
答案 0 :(得分:0)
查询(可能会很贵):
SELECT DISTINCT TOP (1000) t3.CODE AS PRODCODE,
t.CODE AS CODE,
t2.OUTCOST,
t2.LOGICALREF AS LREF,
t2.INSLTRANSREF,
t2.INVENNO,
t2.INTRANSREF,
t2.STTRANSREF
FROM LG_070_01_SERILOTN t
INNER JOIN LG_070_01_SLTRANS t2 ON t2.SLREF = t.LOGICALREF
INNER JOIN LG_070_ITEMS t3 ON t3.LOGICALREF = t.ITEMREF
WHERE t.CODE = '868328002749220'
AND t2.LOGICALREF = (SELECT MAX(tt2.LOGICALREF)
FROM LG_070_01_SERILOTN tt
INNER JOIN LG_070_01_SLTRANS tt2
ON tt2.SLREF = tt.LOGICALREF
INNER JOIN LG_070_ITEMS tt3
ON tt3.LOGICALREF = tt.ITEMREF
WHERE tt.CODE = t.CODE)
示例查询 SQLFIDDLEExample :
SELECT DISTINCT TOP (1000) t.*
FROM Table1 t
WHERE t.LREF = (SELECT MAX(tt.LREF)
FROM Table1 tt
WHERE tt.CODE = t.CODE)
结果:
| PRODCODE | CODE | COST | LREF | ONE | TWHO | THREE | FOUR |
-----------------------------------------------------------------------------
| K-3773 | 868328002749220 | 50,85 | 52276 | 52275 | 9 | 39823 | 39824 |