2016-09-30 58 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

感謝我的朋友請稍候測試解決方案 –