价值发扬光大

时间:2011-03-08 08:57:37

标签: sql sql-server tsql

我有以下SQL查询..

SELECT     dbo.O3.[s.no] AS [O3_Sn.NO], dbo.O5.[s.no] AS [O5_Sn.NO], dbo.O3.O3, dbo.O5.O5,
case when dbo.O3.[s.no] > dbo.O5.[s.no] then 'true' else 'false' end as ComparisonColumn
FROM         dbo.O3 INNER JOIN
                      dbo.O5 ON dbo.O3.[s.no] = dbo.O5.[s.no]

当我跑步时,我的输出低于输出..

O3_Sn.NO    O5_Sn.NO    O3  O5  ComparisonColumn
1          1           10   11  TRUE
2          2           12   13  TRUE
3          3            11  10  FALSE
4          4            13  11  FALSE
5          5            15  16  TRUE
6          6            10  11  TRUE
7          7           12   13  TRUE

我想记住TRUE / False的值,如果重复则应该忽略,直到我得到一个反向情况,即TRUE,False ..和FOR False .. TRUE

下面是我应该得到它..

O3_Sn.NO O5_Sn.NO O3  O5    ComparisonColumn New_Case_Carry_value
1        1      10    11    TRUE             TRUE
2        2      12    13    TRUE             NULL
3        3      11    10    FALSE            FALSE
4        4      13    11    FALSE            NULL
5        5      15    16    TRUE             TRUE
6        6      10    11    TRUE             NULL
7        7      12    13    TRUE             NULL

3 个答案:

答案 0 :(得分:3)

您可以使用row_number()对输出进行排序,以将值与前一记录的值进行比较:

with cIntermediate as (
SELECT dbo.O3.[s.no] AS [O3_Sn.NO], dbo.O5.[s.no] AS [O5_Sn.NO], dbo.O3.O3, dbo.O5.O5, 
       case when dbo.O3.[s.no] > dbo.O5.[s.no] then 'true' else 'false' end 
          as ComparisonColumn,
       rowno = row_number() over 
          (order by dbo.O3.[s.no], dbo.O5.[s.no], dbo.O3.O3, dbo.O5.O5)
FROM   dbo.O3 INNER JOIN dbo.O5 ON dbo.O3.[s.no] = dbo.O5.[s.no] 
)
select i1.*, 
       case when i1.ComparisonColumn = i2.ComparisonColumn then null 
          else i1.ComparisonColumn end as NewCaseCarryValue
from cIntermediate i1
left join cIntermediate i2 on i2.rowno=i1.rowno-1

答案 1 :(得分:1)

好的,我会向你解释这个概念,我相信你能够自己解决这个问题。

您发布的所有真假列的最终结果,需要成为临时表,如此,但带有某种标识列:

SELECT dbo.o3.[s.no]  AS [O3_Sn.NO]
       ,dbo.o5.[s.no] AS [O5_Sn.NO]
       ,dbo.o3.o3
       ,dbo.o5.o5
       ,CASE
          WHEN dbo.o3.[s.no] > dbo.o5.[s.no] THEN 'true'
          ELSE 'false'
        END           AS comparisoncolumn
       , ROW_NUMBER() OVER(ORDER BY dbo.o3.[s.no]) AS ident_col
INTO #temp
FROM   dbo.o3
       INNER JOIN dbo.o5
         ON dbo.o3.[s.no] = dbo.o5.[s.no]

然后您需要做的是从#temp中选择,并以与此处类似的方式自我加入#temp:

SELECT a.*
      , CASE WHEN a.comparisoncolumn = b.comparisoncolumn THEN NULL ELSE a.comparisoncolumn END AS final_comparisoncolumn
FROM #temp a
    LEFT JOIN #temp b ON a.ident_col = b.ident_col - 1

然后执行一个case语句来确定是否需要打印null,或者是true还是false。

玩这个概念,我相信你能够从这里开始工作。

答案 2 :(得分:0)

您可以在表格本身上进行左连接(SN = SN-1)并比较ComparisonColumn