반응형
sql에서 열 아래의 열 합계 가져오기
다음과 같은 질문이 있습니다.
select
product_name,
(select bid_price
from bids
where bid_id = current_bid_id) as final_price
from items
where close_date > '2023/01/01'
and close_date < '2023/02/01';
출력하는 항목:
product_name final_price
ball 20
bat 30
hockey_stick 50
대신 다음 중 하나를 원합니다.
product_name final_price
ball 20
bat 30
hockey_stick 50
total 100
또는
product_name final_price total
ball 20 100
bat 30 100
hockey_stick 50 100
별칭 열이여서 어떻게 해야 할지 고민 중입니다.
우선: 아마도 가격 선택 하위 쿼리.select절은 항상 최대 하나의 행을 반환합니다(쿼리하는 경우 오류가 발생함). 따라서 왼쪽 조인(또는 항상 항목과 일치하는 입찰이 있는 경우 내부 조인으로도 표현할 수 있습니다).
그런 다음 창 함수를 사용하여 모든 가격의 합계를 계산하는 다른 열을 결과 집합에 쉽게 추가할 수 있습니다.
select i.product_name,
b.bid_price as final_price,
sum(b.bid_price) over() as total_price
from items i
left join bids b on b.bid_id = i.current_bid_id
where i.close_date >= '2023-01-01' and i. close_date < '2023-02-01';
제가 날짜 필터링을 약간 바꿨습니다.close_date날짜와 유사한 데이터 유형이며 하루 전체에 대해 필터링할 수 있습니다.
사용해 보십시오.
SELECT
i.product_name,
(SELECT bid_price FROM bids WHERE bid_id = i.current_bid_id) AS final_price,
COUNT(*) AS total_bids,
SUM((SELECT bid_price FROM bids WHERE bid_id = i.current_bid_id)) AS total_price FROM items AS i INNER JOIN bids AS b ON i.current_bid_id = b.bid_id WHERE i.close_date > '2023-01-01' AND i.close_date < '2023-02-01' GROUP BY i.product_name;
사용 가능: GROUP BY WITH ROLUP
select
case when product_name is null then 'TOTAL' else product_name END as product_name,
sum(final_price)
from items
group by product_name with rollup
참조: DBFIDDLE
결과:
| 제품명 | 합계(최종 가격) |
|---|---|
| 공 | 20 |
| 박쥐 | 30 |
| 하키 스틱 | 50 |
| 총 | 100 |
언급URL : https://stackoverflow.com/questions/75705708/get-sum-of-column-below-the-column-in-sql
반응형
'programing' 카테고리의 다른 글
| ASP.NET에 대한 전자 메일 주소 확인 (0) | 2023.06.13 |
|---|---|
| VueNuxtNextServerInit에서 데이터를 로드하지 않습니다. (0) | 2023.06.13 |
| sqlalchemy flush()를 입력하고 ID를 입력하시겠습니까? (0) | 2023.06.13 |
| Oracle에서 고유 인덱스를 생성하면서 null을 무시하려면 어떻게 해야 합니까? (0) | 2023.06.13 |
| 문자열 배열의 값 일치 (0) | 2023.06.13 |