TSQL Group By Column

时间:2016-02-19 19:09:17

标签: sql-server-2008 tsql group-by

我有一个t-sql表,列出了多个地点的协议。

列:

  • STID =商店ID
  • AStatID =协议状态ID(1 =有效)
  • PayModeID =(1 =每日,2 =每周等等。)
  • 然后是每个 PayMode金额
  • 的列

我试图通过每家商店的有效协议获得每月潜在的收入。

这是我到目前为止所得到的,但是我收到错误“Subquery返回的值超过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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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子句。