我正在尝试根据其他几列的信息创建一个计算列,这对我来说很难成为SQL的新人。下面是我试图使用的代码,但它对“Sum(SlotActual + TableActual)As Actual”这一行感到生气。我猜这是因为那些是别名。我想我需要使用子查询,但我不确定,因为我之前没有这样做过。如果可能的话我甚至不想显示SlotActual或TableActual我只需要计算它们然后添加它们以获得实际值。这是在SQL 2008中完成的。如果我遗漏了您需要的任何信息,请告诉我。
Select Ltrim(Rtrim(P.Player_ID)) as "Player ID",
Ltrim(Rtrim(P.FirstName)) as "First Name",
Ltrim(Rtrim(P.LastName)) as "Last Name",
Sum(CashIn) as "Cash In",
Sum(CashOut) as "Cash Out",
Sum(Jackpot) as "Jackpot",
Sum(case when S.StatType = 'Slot' then S.CashIn - S.CashOut - S.JackPot end) as SlotActual,
Sum(case when S.StatType = 'Pit' then S.CashIn + S.ChipsIn + S.FrontIn + S.CreditIn - S.CashOut end) as TableActual,
Sum(SlotActual + TableActual) As Actual
From dbo.CDS_PLAYER as P
Join dbo.CDS_ACCOUNT as A
On P.Player_ID = A.Primary_ID
Join dbo.CDS_STATDAY as S
On P.Player_ID = S.Meta_ID
Where S.GamingDate Between '09/15/2014 12:00:00 AM' and '09/21/2014 11:59:59 PM'
And P.EntryDate Between '09/15/2014 12:00:00 AM' and '09/21/2014 11:59:59 PM'
And S.IDType = 'P'
Group by Ltrim(Rtrim(P.Player_ID)) ,
Ltrim(Rtrim(P.FirstName)),
Ltrim(Rtrim(P.LastName))
我得到的错误信息如下:
Msg 207,Level 16,State 3,Line 3 列名称“SlotActual”无效。 Msg 207,Level 16,State 3,Line 3 列名称“TableActual”无效。
答案 0 :(得分:1)
好的,我现在看到了问题。您无法像这样引用选择的命名字段。
替换:
Sum(SlotActual + TableActual) As Actual
请改为:
(Sum(case when S.StatType = 'Slot' then S.CashIn - S.CashOut - S.JackPot end) +
Sum(case when S.StatType = 'Pit' then S.CashIn + S.ChipsIn + S.FrontIn + S.CreditIn - S.CashOut end)) As Actual
允许空值:
(Sum(ISNULL(case when S.StatType = 'Slot' then S.CashIn - S.CashOut - S.JackPot end), 0) +
Sum(ISNULL(case when S.StatType = 'Pit' then S.CashIn + S.ChipsIn + S.FrontIn + S.CreditIn - S.CashOut end), 0)) As Actual
ISNULL允许在左参数为空时使用值。
如果您的数据允许,您也可以在CASE
为S
没有任何值时为(Sum(case when S.StatType = 'Slot' then S.CashIn - S.CashOut - S.JackPot ELSE 0 end) +
Sum(case when S.StatType = 'Pit' then S.CashIn + S.ChipsIn + S.FrontIn + S.CreditIn - S.CashOut ELSE 0 end)) As Actual
添加其他内容。
{{1}}
答案 1 :(得分:0)
使用这样的包装器:
select X.*, Sum(ISNULL(SlotActual,0) + ISNULL(TableActual,0)) As Actual
From (
Select Ltrim(Rtrim(P.Player_ID)) as "Player ID",
Ltrim(Rtrim(P.FirstName)) as "First Name",
Ltrim(Rtrim(P.LastName)) as "Last Name",
Sum(CashIn) as "Cash In",
Sum(CashOut) as "Cash Out",
Sum(Jackpot) as "Jackpot",
Sum(case when S.StatType = 'Slot' then S.CashIn - S.CashOut - S.JackPot end) as SlotActual,
Sum(case when S.StatType = 'Pit' then S.CashIn + S.ChipsIn + S.FrontIn + S.CreditIn - S.CashOut end) as TableActual,
From dbo.CDS_PLAYER as P
Join dbo.CDS_ACCOUNT as A
On P.Player_ID = A.Primary_ID
Join dbo.CDS_STATDAY as S
On P.Player_ID = S.Meta_ID
Where S.GamingDate Between '09/15/2014 12:00:00 AM' and '09/21/2014 11:59:59 PM'
And P.EntryDate Between '09/15/2014 12:00:00 AM' and '09/21/2014 11:59:59 PM'
And S.IDType = 'P'
Group by Ltrim(Rtrim(P.Player_ID)) ,
Ltrim(Rtrim(P.FirstName)),
Ltrim(Rtrim(P.LastName))
) X