MySQL에서 누적 합계 열 만들기
다음과 같은 테이블이 있습니다.
id count
1 100
2 50
3 10
cumulative_sum이라는 새 열을 추가하고 싶으므로 테이블은 다음과 같습니다.
id count cumulative_sum
1 100 100
2 50 150
3 10 160
이 작업을 쉽게 수행 할 수있는 MySQL 업데이트 설명이 있습니까? 이를 달성하는 가장 좋은 방법은 무엇입니까?
성능이 문제인 경우 MySQL 변수를 사용할 수 있습니다.
set @csum := 0;
update YourTable
set cumulative_sum = (@csum := @csum + count)
order by id;
또는 cumulative_sum
열을 제거하고 각 쿼리에서 계산할 수 있습니다.
set @csum := 0;
select id, count, (@csum := @csum + count) as cumulative_sum
from YourTable
order by id;
이것은 달리는 방법으로 누계를 계산합니다. :)
상관 된 쿼리 사용 :
SELECT t.id,
t.count,
(SELECT SUM(x.count)
FROM TABLE x
WHERE x.id <= t.id) AS cumulative_sum
FROM TABLE t
ORDER BY t.id
MySQL 변수 사용 :
SELECT t.id,
t.count,
@running_total := @running_total + t.count AS cumulative_sum
FROM TABLE t
JOIN (SELECT @running_total := 0) r
ORDER BY t.id
노트 :
- 는
JOIN (SELECT @running_total := 0) r
크로스 조인하고, 분리하지 않고도 변수 선언을 가능SET
명령. r
MySQL은 하위 쿼리 / 파생 된 테이블 / 인라인보기에 대해 테이블 별칭을 필요로합니다.
주의 사항 :
- MySQL 특정; 다른 데이터베이스로 이식 할 수 없음
- 은
ORDER BY
중요하다 순서가 OP와 일치하는지 확인하고 더 복잡한 변수 사용에 더 큰 영향을 미칠 수 있습니다 (IE : MySQL에는없는 psuedo ROW_NUMBER / RANK 기능)
MySQL 8.0 / MariaDB는 windowed를 지원합니다 SUM(col) OVER()
.
SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum
FROM tab;
산출:
┌─────┬──────┬────────────────┐
│ id │ cnt │ cumulative_sum │
├─────┼──────┼────────────────┤
│ 1 │ 100 │ 100 │
│ 2 │ 50 │ 150 │
│ 3 │ 10 │ 160 │
└─────┴──────┴────────────────┘
UPDATE t
SET cumulative_sum = (
SELECT SUM(x.count)
FROM t x
WHERE x.id <= t.id
)
select Id, Count, @total := @total + Count as cumulative_sum
from YourTable, (Select @total := 0) as total ;
샘플 쿼리
SET @runtot:=0;
SELECT
q1.d,
q1.c,
(@runtot := @runtot + q1.c) AS rt
FROM
(SELECT
DAYOFYEAR(date) AS d,
COUNT(*) AS c
FROM orders
WHERE hasPaid > 0
GROUP BY d
ORDER BY d) AS q1
각 삽입 전에 합계를 계산하는 트리거를 만들 수도 있습니다.
delimiter |
CREATE TRIGGER calCumluativeSum BEFORE INSERT ON someTable
FOR EACH ROW BEGIN
SET cumulative_sum = (
SELECT SUM(x.count)
FROM someTable x
WHERE x.id <= NEW.id
)
set NEW.cumulative_sum = cumulative_sum;
END;
|
나는 이것을 시험하지 않았다
tableName에서 cumulative_sum으로 id, count, sum (count) over (count desc로 정렬)를 선택하십시오.
I have used the sum aggregate function on the count column and then used the over clause. It sums up each one of the rows individually. The first row is just going to be 100. The second row is going to be 100+50. The third row is 100+50+10 and so forth. So basically every row is the sum of it and all the previous rows and the very last one is the sum of all the rows. So the way to look at this is each row is the sum of the amount where the ID is less than or equal to itself.
참고URL : https://stackoverflow.com/questions/2563918/create-a-cumulative-sum-column-in-mysql
'program tip' 카테고리의 다른 글
셀에서 UITableViewCell indexPath를 얻는 방법은 무엇입니까? (0) | 2020.11.03 |
---|---|
파이썬 목록의 모든 요소에 논리 연산자를 적용하는 방법 (0) | 2020.11.03 |
장고 비밀번호 생성기 (0) | 2020.11.03 |
Java에서 '(int) (char) (byte) -2'가 65534를 생성하는 이유는 무엇입니까? (0) | 2020.11.03 |
다음 위치 후 원격 파일 이름을 가져 오기 위해 컬 (0) | 2020.11.03 |