2016-02-19 73 views
0

我有一個t-sql表列出了多個位置的協議。TSQL組按列

色譜柱:

  • STID =商店ID
  • AStatID =協議狀態ID(1 =活動)
  • PayModeID =(1每日=,2 =每週,等等。)
  • 然後每個的PayMode的列達

我試圖讓我們每月潛在來自活躍協議,每家商店的收入。

這是我到目前爲止,但我得到的錯誤「子查詢返回多個值1」

我哪裏錯了?

SET NOCOUNT ON 
Declare @dPotential Money, 
    @wPotential Money, 
    @bPotential Money, 
    @sPotential Money, 
    @mPotential Money, 
    @Potential Money; 

Set @dPotential = (((Select Agreemnt.DailyRate FROM Agreemnt WHERE Agreemnt.PayModeID = 1 And Agreemnt.AStatID = 1)*365)/12) 
Set @wPotential = (((Select Agreemnt.WeeklyRate FROM Agreemnt WHERE Agreemnt.PayModeID = 2 And Agreemnt.AStatID = 1)*52)/12) 
Set @bPotential = (((Select Agreemnt.WeeklyRate FROM Agreemnt WHERE Agreemnt.PayModeID = 3 And Agreemnt.AStatID = 1)*52)/12) 
Set @sPotential = (((Select Agreemnt.DailyRate FROM Agreemnt WHERE Agreemnt.PayModeID = 4 And Agreemnt.AStatID = 1)*24)/12) 
Set @mPotential = ((Select Agreemnt.DailyRate FROM Agreemnt WHERE Agreemnt.PayModeID = 5 And Agreemnt.AStatID = 1)* 12) 

Set @Potential = @dPotential + @wPotential + @bPotential + @sPotential + @mPotential 

Select Agreemnt.STID, @Potential From Agreemnt 
Group By Agreemnt.STID 
+1

這些查詢到您的變量分配值來返回多行多 – Lamak

回答

1

嘗試是這樣的:

SELECT 
    a.STID, 
    SUM(
    CASE a.PayModeID 
     WHEN 1 THEN a.DailyRate * 365/12 
     WHEN 2 THEN a.WeeklyRate * 52/12 
     WHEN 3 THEN a.WeeklyRate * 52/12 
     WHEN 4 THEN a.DailyRate * 24/12 
     WHEN 5 THEN a.DailyRate * 12 
    END) as Potential 
FROM Agreemnt a 
WHERE a.AStatID = 1 
GROUP BY a.STID 
+0

你是一個刻着天才!我愛你!大聲笑 – thelincster

0

這是一個數據問題。您需要查看其中哪些返回多個值以及爲什麼。使用這些qeres看到的數據是什麼:

Select * FROM Agreemnt WHERE Agreemnt.PayModeID = 1 And Agreemnt.AStatID = 1 
Select * FROM Agreemnt WHERE Agreemnt.PayModeID = 2 And Agreemnt.AStatID = 1 
Select * FROM Agreemnt WHERE Agreemnt.PayModeID = 3 And Agreemnt.AStatID = 1 
Select * FROM Agreemnt WHERE Agreemnt.PayModeID = 4 And Agreemnt.AStatID = 1 
Select * FROM Agreemnt WHERE Agreemnt.PayModeID = 5 And Agreemnt.AStatID = 1 

注意我用SELECT *這裏,因爲它很可能會在表中的其他領域之一是造成重複。修復將取決於數據的含義。這可能意味着您需要使用聚合函數或附加的where子句。