从派生表sql异常中选择

时间:2013-05-27 06:33:49

标签: sql sql-server sql-server-2005

我正在尝试从派生表中执行select语句,如下所示:在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)

感谢您的帮助。

1 个答案:

答案 0 :(得分: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

计划图

enter image description here