我试图在视图中创建一个总和,该总和是根据另一个列除以与ID匹配的行数计算得出的。 例: 总计=表1 /(ROWS,其中ID =相同)
到目前为止的观点是:
Create View testview AS (
SELECT t2.ID,t1.Sum1 FROM
Table1 t1
LEFT JOIN
Table2 t2
ON
t1.ID = t2.ID
);
下面是一个表格示例:
+-------+---------+--------+
| T2.ID | T1.Sum1 | Total |
+-------+---------+--------+
| 1 | 10.00 | 10.00 |
| 2 | 15.00 | 15.00 |
| 3 | 20.00 | 10.00 |
| 3 | 20.00 | 10.00 |
| 4 | 30.00 | 10.00 |
| 4 | 30.00 | 10.00 |
| 4 | 30.00 | 10.00 |
+-------+---------+--------+
谢谢
答案 0 :(得分:1)
试试这个。将Aggregate count
与Window function
一起使用,可以计算每个sum1
中ID
的数量,并使用它来划分sum1
CREATE TABLE #sum
(
ID INT,
Sum1 NUMERIC(4, 2)
)
INSERT #sum
VALUES (1,10.00 ),
(2,15.00 ),
(3,20.00 ),
(3,20.00 ),
(4,30.00 ),
(4,30.00 ),
(4,30.00 )
SELECT *,
Sum1 / Count(id)
OVER (
partition BY id) AS Total
FROM #sum
查看应该是这样的。
CREATE VIEW testview
AS
(SELECT t2.ID,
t1.Sum1,
t1.Sum1 / Count(t2.id)OVER (partition BY id) AS Total
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.ID = t2.ID);