查询从一个表连接多个列

时间:2015-07-14 20:28:33

标签: sql-server tsql join

我试图比较来自同一个表的3个不同数据的值。我获取信息的表包含列DescriptionID,DateTime和Data。我想比较dateTime为+或 - 相隔一分钟时不同DescriptionID的数据值。我使用连接来执行两个描述ID,如下所示:

Gini = area_perfect - area_lorenz

我认为我可能只是在我加入上面的内容时再进行另一次连接,然后再次选择Select查询。但是,这似乎不起作用。

我对SQL很陌生,所以如果我走的方向完全错误,请告诉我。

更改为:

Select a.DescriptionID, b.DescriptionID, a.Data, a.DateTime as 'DataA',b.Data as 'DataB' 
From(
SELECT TOP 1000 [DescriptionID]
      ,[MachineID]
      ,[DateTime]
      ,[Data]
  FROM [ACQDATA].[dbo].[AlarmData] where DescriptionID =1014 order by dateTime desc )
  as a
  inner join (
  SELECT TOP 1000 [DescriptionID]
      ,[MachineID]
      ,[DateTime]
      ,[Data]
  FROM [ACQDATA].[dbo].[AlarmData] where DescriptionID=1914  order by dateTime desc 
  ) as b 
  on a.DateTime BETWEEN (DATEADD(minute, -1,  b.Datetime))  AND (DATEADD(minute, 1,  b.Datetime))

  where b.Data='True'or b.Data = 'False'

现在我该如何使用myData 1005?

1 个答案:

答案 0 :(得分:1)

使用保留字作为列名(“DateTime”)不是一个好主意...

但是 - 无论如何 - 这可能有所帮助:

我使用CTE处理您的子集,就好像它们是自置表一样。 它完全未经测试 - 实际上 - 我无法想象你真正想要的东西......: - )

WITH myData1014 AS
(
    SELECT TOP 1000 [DescriptionID]
      ,[MachineID]
      ,[DateTime]
      ,[Data]
    FROM [ACQDATA].[dbo].[AlarmData] where DescriptionID =1014 order by dateTime desc 
)
,myData1914 AS
(
    SELECT TOP 1000 [DescriptionID]
      ,[MachineID]
      ,[DateTime]
      ,[Data]
      ,DATEADD(MINUTE,1,[DateTime]) AS DatPlus1
      ,DATEADD(MINUTE,-1,[DateTime]) AS DatMinus1
    FROM [ACQDATA].[dbo].[AlarmData] where DescriptionID =1914 order by dateTime desc 
)
,myData1005 AS
(
 SELECT TOP 1000 [DescriptionID]
      ,[MachineID]
      ,[DateTime]
      ,[Data]
      ,DATEADD(MINUTE,1,[DateTime]) AS DatPlus1
      ,DATEADD(MINUTE,-1,[DateTime]) AS DatMinus1
    FROM [ACQDATA].[dbo].[AlarmData] where DescriptionID =1005 order by dateTime desc 
)
SELECT *
FROM myData1014
OUTER APPLY
(
    SELECT Data
    FROM myData1914
    WHERE myData1014.[DateTime] BETWEEN myData1914.DatMinus1 AND myData1914.DatPlus1 
) AS Details1914
OUTER APPLY
(
    SELECT Data
    FROM myData1005
    WHERE myData1014.[DateTime] BETWEEN myData1005.DatMinus1 AND myData1005.DatPlus1 
) AS Details1005
Where Details1914.Data='True' or Details1914.Data='False' --True OR False will always be true ???