如果我有这张表
PID Phase CtrlDollars ActualDollars
-----------------------------------------------
1 A 25.00 50.00
1 B 10.00 23.00
1 c 2.00 14.00
2 A 24.00 24.00
2 B 10.00 20.00
我怎样才能写一个选择给我一个
Total for the Actual Dollars for each PID (TotalActDollsForPID)
但仍然显示详细信息(这是客户想要的)
PID Phase CtrlDollars ActualDollars TotalActDollsForPID
----------------------------------------------------------------------
1 A 25.00 50.00 87.00
1 B 10.00 23.00 87.00
1 c 2.00 14.00 87.00
2 A 24.00 24.00 44.00
2 B 10.00 20.00 44.00
答案 0 :(得分:2)
使用子查询:
SELECT p.PID,
p.PHASE,
p.CtrlDollars,
p.ActualDollars,
t.TotalActDollsForPID
FROM mytable p
INNER JOIN
(SELECT PID,
SUM(ActualDollars) AS TotalActDollsForPID
FROM mytable GROUP BY PID) AS t
ON t.PID = p.PID
答案 1 :(得分:2)
如果您有SQL Server 2005+,则可以使用the OVER()
clause。
SELECT PID,
Phase,
CtrlDollars,
ActualDollars,
SUM(ActualDollars) OVER(PARTITION BY PID) AS "TotalActDollsForPID"
FROM MyTable
答案 2 :(得分:0)
除了使用子查询和窗口函数之外,另一个选项是使用apply
:
SELECT
PID,
Phase,
CtrlDollars,
ActualDollars,
TotalActDollsForPID
FROM Table1 t
OUTER APPLY (
SELECT
SUM(actualdollars) AS TotalActDollsForPID
FROM Table1
WHERE PID = t.PID
GROUP BY pid
) oa
它可能会提供更好的性能(或者不是,ymmv)。