2016-09-30 34 views
0

我在sql server是新,写两个查询,第一个选择查询此:
如何编写查询表单计算两个select查询减号?

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... 


如何为此目的编写查询,谢谢大家。

回答

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 
+0

感谢我的朋友请稍候测试解决方案 –