如何比较2行数据并在第3行显示结果?

时间:2014-04-23 02:40:26

标签: sql sql-server

我试图计算2行之间的差异,e / g:

Row1: 1, "Brazil", 3, 4, 5
Row2: 2, "Brazil", 5, 6, 6
Row3: 1, "Brazil", 2, 2, 1

这是我比较的查询示例:

SELECT
    '3' as RowNumber,t1.Country ,t2.col1 -t1.col1 AS Col1Diff ,t2.col2 -t1.col2 AS Col2Diff,t2.col3 -t1.col3 AS Col3Diff 
FROM        (SELECT 1 as RowNumber,'Brazil' as Country,2 As col1,3 As col2,5 As col3)AS T1
INNER JOIN ( SELECT 2 as RowNumber,'Brazil' as Country,5 As col1,6 As col2,6 As col3)AS T2 on T1.Country = T2.Country

第一行和第二行按不同表的结果分组,我需要第三行显示不同。我在同一个表方法上尝试了内连接,但它的行为并不像我希望的那样。

我只能拥有不同的行,我丢失了第1行和第2行。当然我可以再次选择和UNION,但考虑到性能问题。这不是一个好主意。

有人对此有所了解吗?

我正在使用SQL Server 2008 R2

1 个答案:

答案 0 :(得分:0)

最佳解决方案是制作一个临时表。在该临时表中插入两行。而不需要多次联合查询。使用临时表你可以做联合操作。它比使用union与查询更好。

如下例所示。

Declare @tab Table (RowNumber Smallint, Country Varchar(10), Col1 Smallint, Col2 Smallint, Col3 Smallint)
Insert Into @tab
SELECT 1 as RowNumber,'Brazil' as Country,2 As col1,3 As col2,5 As col3

Insert Into @tab
SELECT 2 as RowNumber,'Brazil' as Country,5 As col1,6 As col2,6 As col3

Select *
From @tab
UNION
Select '3' as RowNumber,
    Fir.Country,
    Sec.col1 - Fir.col1 AS Col1Diff,
    Sec.col2 -Fir.col2 AS Col2Diff,
    Sec.col3 -Fir.col3 AS Col3Diff 
From @tab Fir
Left Join @tab Sec On Sec.RowNumber = 2
Where Fir.RowNumber = 1

你的输出就像这样。

RowNumber   Country Col1    Col2    Col3
   1        Brazil  2        3       5
   2        Brazil  5        6       6
   3        Brazil  3        3       1