时间:2015-11-17 17:13:29

标签: sql-server-2008

我正在尝试找到每一列的第2行和第1行(2-1)之间的区别,我对如何处理这个问题感到迷茫,我可能从一开始就做错了我所知道的。 2个子查询返回我感兴趣的行,其余的是我试图将它们放在一个表中以对它们进行操作,但需要方向ATM

SELECT  ROW_NUMBER() OVER(ORDER BY totalhopper_01 ASC) AS rownum,TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06 FROM 
(

SELECT * FROM(
SELECT TOP 1 TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06 FROM mm_Cycle_Data
 WHERE TotalHopper_01 IS NOT NULL
 AND TotalHopper_02 IS NOT NULL  
 AND TotalHopper_03 IS NOT NULL 
 AND TotalHopper_05 IS NOT NULL 
 AND TotalHopper_06 IS NOT NULL 
 AND  get_address=38 AND t_stamp> '2015-10-28 07:00:00' ORDER BY t_stamp ASC)a

 UNION

 SELECT * FROM (
SELECT TOP 1 TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06 FROM mm_Cycle_Data
 WHERE 
 TotalHopper_01 IS NOT NULL
 AND TotalHopper_02 IS NOT NULL  
 AND TotalHopper_03 IS NOT NULL 
 AND TotalHopper_05 IS NOT NULL 
 AND TotalHopper_06 IS NOT NULL 
 AND get_address=38 AND t_stamp> '2015-11-17 07:00:00' ORDER BY t_stamp ASC)b
 )c

结果

rownum               TotalHopper_01 TotalHopper_02 TotalHopper_03 TotalHopper_05 TotalHopper_06
-------------------- -------------- -------------- -------------- -------------- --------------
1                    182450272      8343796        2539352        0              0
2                    339742596      19222977       4940526        0              0

1 个答案:

答案 0 :(得分:0)

或许创建临时表并首先填充所需数据然后运行查询??

INSERT INTO #TempTable (TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06)
select TOP 1 TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06  
FROM mm_Cycle_Data
WHERE TotalHopper_01 IS NOT NULL
 AND TotalHopper_02 IS NOT NULL  
 AND TotalHopper_03 IS NOT NULL 
 AND TotalHopper_05 IS NOT NULL 
 AND TotalHopper_06 IS NOT NULL 
 AND  get_address=38 AND t_stamp> '2015-10-28 07:00:00' ORDER BY t_stamp ASC

INSERT INTO #TempTable   (TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06)
select TOP 1    TotalHopper_01,TotalHopper_02,TotalHopper_03,TotalHopper_05,TotalHopper_06  
FROM mm_Cycle_Data
WHERE  TotalHopper_01 IS NOT NULL
 AND TotalHopper_02 IS NOT NULL  
 AND TotalHopper_03 IS NOT NULL 
 AND TotalHopper_05 IS NOT NULL 
 AND TotalHopper_06 IS NOT NULL 
 AND get_address=38 AND t_stamp> '2015-11-17 07:00:00' ORDER BY t_stamp ASC

-- get summary of data
SELECT SUM(TotalHopper_01) as totalHopper_01,SUM(TotalHopper_02) as totalHopper_02  
FROM #TempTable

-- clean up the temp table when finished
DROP TABLE #TempTable