获取下一列sql中的列总和

时间:2016-05-26 13:39:36

标签: sql group-by sql-server-2014 rollup



<table border="1">
  <tr><th>Pcode</th><th>TCode</th><th>TName</th><th>CCode</th><th>Rate</th><th>Total=sum(rates of all PCodes)</th></tr>
  <b><tr><td>12345</td><td>200</td><td>200</td><td>12</td><td>2000</td><td>8000</td></tr>
  <tr><td>12345</td><td>201</td><td>200</td><td>12</td><td>1000</td><td>8000</td></tr>
  <tr><td>12345</td><td>202</td><td>200</td><td>12</td><td>2000</td><td>8000</td></tr>
  <tr><td>12345</td><td>205</td><td>200</td><td>12</td><td>3000</td><td>8000</td></tr>
  <tr><td>12346</td><td>200</td><td>200</td><td>12</td><td>4000</td><td>32000</td></tr>
  <tr><td>12346</td><td>204</td><td>200</td><td>12</td><td>5000</td><td>32000</td></tr>
  <tr><td>12346</td><td>208</td><td>200</td><td>12</td><td>5000</td><td>32000</td></tr>
  <tr><td>12346</td><td>1235</td><td>200</td><td>12</td><td>3000</td><td>32000</td></tr>
  <tr><td>12346</td><td>12</td><td>200</td><td>12</td><td>7000</td><td>32000</td></tr>
  <tr><td>12346</td><td>100</td><td>200</td><td>12</td><td>8000</td><td>32000</td></tr>
  
</table>
<p>I have a table with Pcode, Tcode, TName, CCode, Rate. Need to find the sum under Pcode as Total in next column</p>
&#13;
&#13;
&#13;

我想要这个表格列&#39;(总计)&#39;与下表(SQL)中的所有列一起提取。

我已经尝试过ROLLUP并且没有解决方案。

由Pcode分组的总数并将该总和输入下一列。

TIA,

2 个答案:

答案 0 :(得分:0)

With your_table_CTE as (
    select C.x,A.y,B.x from DFG inner join A, inner join B, inner join C
)

select a.pcode, a.TCode, a.TName, a.CCode, a.Rate, b.Total
from your_table_CTE a
join (
  select pcode, sum(rate) as Total
  from your_table_CTE
  group by pcode
) b
on a.pcode = b.pcode

答案 1 :(得分:0)

您只需要使用GROUP BY。此解决方案使用公用表表达式(将tempTable替换为表的名称):

;WITH TotalByPCode (PCode, Total) AS (
    SELECT PCode, SUM(Rate) FROM tempTable GROUP BY PCode
    )

SELECT R.PCode, R.TCode, R.TName, R.CCode, R.Rate, T.Total
FROM tempTable R JOIN TotalByPCode T ON R.PCode = T.PCode
;