2

我试图编写我认为是相当复杂的 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'

我需要修改第二个查询,使其还包括 * from 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)
4

2 回答 2

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 ))
于 2013-04-25T02:51:53.370 回答
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 ) )
于 2013-04-25T03:27:27.983 回答