复杂查询限制SQL知识

时间:2013-04-25 02:04:47

标签: sql sql-server

我试图写出我认为是一个相当复杂的SQL查询,但我正在使用有限的SQL知识。我有这个问题:

 SELECT 
   analysisvalue.analysisid, 
   heatname, 
   analysistime, 
   sampletype,
   grade, 
   productid, 
   element, 
   value 
 FROM 
   dbo.AnalysisValue 
 INNER JOIN 
   dbo.CAnalysis 
 ON 
   dbo.AnalysisValue.AnalysisID = dbo.CAnalysis.AnalysisID
 WHERE 
   heatname = 'A7M0066' 
 ORDER BY 
   analysisvalue.analysisid ASC, 
   element

和这个查询:

SELECT 
  * 
FROM 
  S_analysis 
WHERE 
  heat_no = 'A7M0066'

我需要修改第二个查询以包含*来自S_analysis WHERE heat_no ='A7M0066',还包括那些没有那个heat_no的记录,其中analysis_datetime介于第一个查询的最后一个记录的分析时间和两个小时之间跟着那个时间。

第二个查询的S_analysis表结构是:

analysis_datetime(datetime, not null)
heat_no(varchar(7), not null)
comment(varchar(40), null)
Then about 30 other columns of type (real, null)

第一个查询中AnalysisValue的表结构是:

AnalysisID(int, not null)
Element(char(9), not null)
Value(real, null)

第一个查询中CAnalysis的表结构是:

AnalysisID(PK, int, not null)
HeatName(char(7), null)
AnalysisTime(datetime, null)
SampleType(char(5), null)
Grade(char(4), null)
ProductID(char(14), null)

2 个答案:

答案 0 :(得分:0)

由于您只需要第一个查询的第一行。您可以使用Cross join和第二个查询来获得所需的结果

 ;with cte as 
(SELECT 
 analysisvalue.analysisid, 
 heatname, 
 analysistime, 
 sampletype,
 grade, 
 productid, 
 element, 
 value 
 FROM 
 dbo.AnalysisValue 
 INNER JOIN 
 dbo.CAnalysis 
 ON 
 dbo.AnalysisValue.AnalysisID = dbo.CAnalysis.AnalysisID
 WHERE 
 heatname = 'A7M0066' 
 )
 SELECT 
      * 
 FROM 
 S_analysis s
 CROSS JOIN (SELECT TOP 1 analysistime
 FROM cte
 ORDER BY analysisid desc
 ) c
 WHERE s.heat_no = 'A7M0066' OR
 (s.analysis_datetime BETWEEN c.analysistime AND DATEADD(hh, 2, c.analysistime ))

答案 1 :(得分:0)

试试这个(从未使用sql-server,但它应该会产生预期的结果)

SELECT 
  * 
FROM 
  S_analysis 
  CROSS JOIN 
  ( 
    SELECT TOP 1
      analysistime
    FROM 
       dbo.CAnalysis 
    WHERE 
       heatname = 'A7M0066' 
    ORDER BY 
      analysistime DESC ) c
WHERE 
  heat_no = 'A7M0066'
  OR ( heat_no IS NULL AND s.analysis_datetime BETWEEN c.analysistime AND DATEADD(hh, 2, c.analysistime ) )