2

我正在尝试在 MSSQL SERVER 2005 中从派生表中执行如下选择语句:

我试图解决的问题是存在重复的行,但它们在 DATE 字段中的差异以秒为单位,但我会考虑几分钟

ID  DATE
1   08:20:00
1   08:20:01
2   09:21:00
5   10:00:00
5   10:00:01

我想获取 ID 的 DISTINCT 值,并按 DATE 排序,但是当我按日期排序时,我需要包含 DATE 字段。所以我不能在一列上明确选择。

派生表查询(自行完美检索重复项)

SELECT  p.[SICIL] AS ID, h.[ZAMAN_TRH] AS ZAMAN_TRH
FROM [RF_BIO].[dbo].[PERSONEL] p,  [RF_BIO].[dbo].[HAREKETLER] h  
WHERE h.[ZAMAN_TRH] > '2013-05-27T00:00:00.000' AND h.[YON]= 2 AND 
(p.[KARTNO] = h.[KARTNO] OR p.[SICIL]= h.[SICIL]) 
ORDER BY h.[ZAMAN_TRH] DESC 

使用派生表的查询:

SELECT DISTINCT [SICIL] 
FROM ( SELECT  p.[SICIL] AS SICIL, h.[ZAMAN_TRH] AS ZAMAN_TRH  
FROM [RF_BIO].[dbo].   [PERSONEL] p,  [RF_BIO].[dbo].[HAREKETLER] h 
WHERE h.[ZAMAN_TRH] > '2013-05-27T00:00:00.000' AND h.[YON]= 2 AND 
(p.[KARTNO] = h.[KARTNO] OR p.[SICIL]= h.[SICIL]) ORDER BY h.[ZAMAN_TRH] DESC ) AS LAST

这让我在 Java 中出现 sql 异常

java.sql.SQLException:  
    at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
    at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2893)
    at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2335)
    at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:638)
    at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
    at net.sourceforge.jtds.jdbc.JtdsStatement.executeQuery(JtdsStatement.java:1427)

感谢您的帮助。

4

1 回答 1

2

在 ORDER BY 子句中使用 GROUP BY 子句和聚合函数

SELECT p.[ID] AS ID
FROM [RF_BIO].[dbo].[PERSONEL] p, [RF_BIO].[dbo].[HAREKETLER] h  
WHERE h.[DATE] > '2013-05-27T00:00:00.000' AND h.[YON]= 2
  AND (p.[KART] = h.[KART] OR p.[ID]= h.[ID])
GROUP BY p.[ID]
ORDER BY MAX(h.[DATE]) DESC 

SQLFiddle上的简单演示

SELECT p.[SICIL] AS SICIL
FROM [RF_BIO].[dbo].[PERSONEL] p, [RF_BIO].[dbo].[HAREKETLER] h 
WHERE h.[ZAMAN_TRH] > '2013-05-27T00:00:00.000' AND h.[YON]= 2
  AND (p.[KARTNO] = h.[KARTNO] OR p.[SICIL]= h.[SICIL])
GROUP BY p.[SICIL]  
ORDER BY MAX(h.[ZAMAN_TRH]) DESC

平面图

在此处输入图像描述

于 2013-05-27T06:42:25.860 回答