如何编写查询表单计算两个选择查询减号?

时间:2016-09-30 10:09:43

标签: sql-server

我是sql server的新用户,写了两个查询,首先选择查询:

select [Cycle],count([Price]) as countbehi 
from [ClubEatc].[dbo].[CycleAnalysisTable]
where cast([Price] as float)<cast('0' as float) and 
      (cast([Telno] as bigint)>=04137626838 and cast([Telno] as bigint)<=04137629000)
group by [Cycle]


告诉我这个结果:

    Cycle          countbehi 
941     -942        841
942     -943        968
943     -944        1238
944     -945        785
945     -946        1369
951     -952        1223


第二个查询:

select [Cycle],count([Price]) as countbehi 
from [ClubEatc].[dbo].[CycleAnalysisTable]
where cast([Price] as float)>cast('0' as float) and 
      (cast([Telno] as bigint)>=04137626838 and cast([Telno] as bigint)<=04137629000)
group by [Cycle]


并告诉我这个:

    Cylce          countbehi 
941     -942        962
942     -943        821
943     -944        848
944     -945        1014
945     -946        732
951     -952        880


我想写查询告诉我这一步:

-run select query#1
-run select query#2
-if (query#1 countbehi-query#2 countbehi)>0 then show me in result.


如果想要解释一下真的例子:

in query#1 countbehi=841 and in query#2 countbehi=962-->minus=-121 then not show in result.
in query#1 countbehi=968 and in query#2 countbehi=821-->minus=147 then show in result.
and...


我怎么能为此目的编写查询,谢谢大家。

1 个答案:

答案 0 :(得分:0)

试试这个脚本:

SELECT Query1.* FROM(
    select [Cycle],count([Price]) as countbehi 
    from [ClubEatc].[dbo].[CycleAnalysisTable]
    where cast([Price] as float)<cast('0' as float) and 
          (cast([Telno] as bigint)>=04137626838 and cast([Telno] as bigint)<=04137629000)
    group by [Cycle]
)Query1
INNER JOIN (
    select [Cycle],count([Price]) as countbehi 
    from [ClubEatc].[dbo].[CycleAnalysisTable]
    where cast([Price] as float)>cast('0' as float) and 
          (cast([Telno] as bigint)>=04137626838 and cast([Telno] as bigint)<=04137629000)
    group by [Cycle]
)Query2 ON Query1.[Cycle]=Query2.[Cycle] 
WHERE (Query1.countbehi - Query2.countbehi) > 0