我有一个当前查询,它返回查询参数的所有值。
但是当我只想显示每个最新行时,它会返回较旧的值,我已经开始使用max()
和DISTINCT
,但我无法获得输出我想要
当前代码
SELECT
IME.TP AS [Time],
IU.FS07 AS [LID],
IU.I AS [LNum],
IME.TPL AS [Location],
(SELECT CASE
WHEN IME.TPL = 'Y'
THEN 'GTG'
ELSE
(SELECT CASE
WHEN IME.TPL = 'V'
THEN 'WAIT'
ELSE 'WAIT'
END)
END) AS [Go To]
FROM
IU
INNER JOIN IUFV ON IU.G = IUFV.UG
INNER JOIN IME ON IUFV.G = IME.UFVG
当前输出
________________________________________________________________
|Time LID LNum Location Go To|
|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
|2012-07-08 10:54:57.837 CCC CCC111 V WAIT |
|2012-07-08 12:15:07.000 CCC CCC111 Y GTG |
|2012-07-17 06:58:33.417 CCC CCC111 T WAIT |
|2012-08-09 03:51:20.750 BBB BBB222 Y GTG |
|2012-08-09 04:06:13.473 BBB BBB222 Y GTG |
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
所需输出
________________________________________________________________
|Time LID LNum Location Go To|
|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|
|2012-07-17 06:58:33.417 CCC CCC111 T WAIT |
|2012-08-09 04:06:13.473 BBB BBB222 Y GTG |
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
答案 0 :(得分:1)
SELECT
IME.TP AS [Time],
IU.FS07 AS [LID],
IU.I AS [LNum],
IME.TPL AS [Location],
(SELECT CASE
WHEN IME.TPL = 'Y'
THEN 'GTG'
ELSE 'WAIT'
END) AS [Go To]
FROM
IU
INNER JOIN IUFV ON IU.G = IUFV.UG
INNER JOIN IME ON IUFV.G = IME.UFVG
INNER JOIN (Select Max(time) MTime, UFVG from IME
GROUP BY UFVG) B
on B.UFVG=IUFV.G
and B.MTime = IME.Time
如果没有更深入的潜水,我不确定是否可以消除额外的连接,并且首先从IME获得结果。但是对TPL的需求可能需要单独的连接
SELECT
IME.TP AS [Time],
IU.FS07 AS [LID],
IU.I AS [LNum],
IME.TPL AS [Location],
(SELECT CASE
WHEN IME.TPL = 'Y'
THEN 'GTG'
ELSE 'WAIT'
END) AS [Go To]
FROM
IU
INNER JOIN IUFV ON IU.G = IUFV.UG
INNER JOIN (Select Max(time) MTime, UFVG from IME
GROUP BY UFVG) B
on B.UFVG=IUFV.G
and B.MTime = IME.Time
答案 1 :(得分:0)
这是基本方法。我假设您在组中没有重复的时间戳。
select *
from T
inner join (select GrpId, max(TimeStmp) from T group by GrpId) as MaxT
on MaxT.GrpId = T.GrpId and T.TimeStmp = MaxT.TimeStmp