3 개의 테이블 (Transaction, TransactionEntry 및 TenderEntry)이 있습니다. SQL 쿼리를 실행할 때 TransactionEntry Table 때문에 합계 값을 두 번 얻었습니다.
그래서 제가 2 개의 아이템을 가지고 있다고합시다 (옷은 $ 288.75, 무료 우산은 $ 50.00). $ 300 상당의 현금과 $ 100 상당의 GC를 사용하여 지불을 정산했습니다. 이제 $ 61.25 상당의 현금 변경이 있습니다.
다음은 3 개의 테이블에있는 항목입니다.
거래 테이블
TransactionNumber|Total|
========================
1 |338.75|
TransactionEntry 테이블
TransactionNumber|ItemID|Price|
===============================
1 |245648|288.75|
1 |129 |50.00 |
입찰 입장 테이블
TransactionNumber|TenderID|Description|Amount|
==============================================
1 |1 |Cash |300.00|
1 |1 |Cash |-61.25|
1 |20 |GC |100.00|
지금까지 제가 만든 것입니다
select [Transaction].TransactionNumber,
(case when [Transaction].RecallType = 0 then [Transaction].total else 0 end) as Sales,
sum(case when TransactionEntry.ItemID = 6922 then TransactionEntry.Price
when TransactionEntry.price = 0 then TransactionEntry.price else 0 end) as Free,
sum(case when TenderEntry.tenderID = 1 then TenderEntry.Amount else 0 end) as Cash,
sum(case when TenderEntry.tenderID = 20 then TenderEntry.Amount else 0 end) as GC
from [Transaction] inner join
TransactionEntry on [Transaction].transactionnumber = TransactionEntry.transactionnumber inner join
TenderEntry on [Transaction].transactionnumber = TenderEntry.transactionnumber
group by [Transaction].TransactionNumber,
(case when [Transaction].RecallType = 0 then [Transaction].total else 0 end)
이런 종류의 출력을 얻습니다.
TransactionNumber|Sales |Free |Cash |GC |
==============================================
1 |338.75|150.00|477.50|200.00|
이 대신
TransactionNumber|Sales |Free |Cash |GC |
==============================================
1 |338.75|50.00|238.75 |100.00|
트랜잭션 당 하나의 행을 원하므로 다음과 같이 조인을 수행하기 전에 조인 된 테이블을 트랜잭션 수준으로 합산하는 것이 좋습니다.
select t1.TransactionNumber,
case when t1.RecallType = 0 then t1.total else 0 end as Sales,
t2.Free,
t3.Cash,
t3.GC
from [Transaction] t1
inner join (select transactionnumber,
sum(case when ItemID = 6922 then Price else 0 end) as free
from TransactionEntry
group by transactionnumber) as t2
on t1.transactionnumber = t2.transactionnumber
inner join (select transactionnumber,
sum(case when tenderID = 1 then Amount else 0 end) as Cash,
sum(case when tenderID = 20 then Amount else 0 end) as GC
from TenderEntry
group by transactionnumber) as t3
on t1.transactionnumber = t3.transactionnumber
테이블 별칭 (t1, t2, t3)을 사용하여 코드를 압축하고 좀 더 쉽게 읽을 수 있도록했습니다. "트랜잭션"이 예약어 인 것처럼 보이므로 참조 할 때 항상 대괄호를 사용하여 이름을 묶어야하므로 테이블 이름을 선택하는 것이 좋지 않을 수 있습니다.
이 코드에 문제가있는 것 같습니다.
sum(case when TransactionEntry.ItemID = 6922 then TransactionEntry.Price
when TransactionEntry.price = 0 then TransactionEntry.price else 0 end) as Free,
무료라고 말하는 우산은 6922가 아니라 129 항목이기 때문입니다. 또한 "TransactionEntry.price = 0 then ..."은 가격에 관계없이 가격을 0으로 설정합니다. 당신이 거기서 무엇을 의도했는지 잘 모르겠습니까?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다