如何减去where子句中的数字?

时间:2016-01-28 01:20:52

标签: sql sql-server sql-server-2012

我有两张桌子,

tab1

enter image description here

tab2

enter image description here

我希望结果number中的条件tab1大于1,然后来自number的{​​{1}}的结果减去1。 我试过这段代码,

tab2

并且它显示如下

enter image description here

但我希望得到像这样的结果

enter image description here

我怎样才能得到这样的结果?我想是这样的

SELECT T1.users AS UsrT1, T1.number AS NumT1, T2.users AS UsrT2, T2.number AS NumT2, T2.number - 1 AS NumT2_Min_1 
FROM tab1 T1 INNER JOIN tab2 T2 ON T1.id = T2.id
WHERE T1.number > 1

但这完全是一个错误。

1 个答案:

答案 0 :(得分:1)

您希望过滤计算值numt2_min_1)。在Outer query

中进行过滤
WITH cte 
     AS (SELECT T1.users      AS UsrT1, 
                T1.number     AS NumT1, 
                T2.users      AS UsrT2, 
                T2.number     AS NumT2, 
                T2.number - 1 AS NumT2_Min_1 
         FROM   tab1 T1 
                INNER JOIN tab2 T2 
                        ON T1.id = T2.id) 
SELECT * 
FROM   cte 
WHERE  numt2_min_1 > 1 

或只是

SELECT T1.users      AS UsrT1, 
       T1.number     AS NumT1, 
       T2.users      AS UsrT2, 
       T2.number     AS NumT2, 
       T2.number - 1 AS NumT2_Min_1 
FROM   tab1 T1 
       INNER JOIN tab2 T2 
               ON T1.id = T2.id 
WHERE  T2.number - 1 > 1