我有这三个表
ITEM 表:
ITEM_ID AMOUNT_DUE SERVICE_CHARGE
-----------------------------------
1 1000 100
投标表:
ITEM_ID TYPE_ID AMOUNT
-------------------------------
1 0 600
1 1 500
TYPE 表格:
TYPE_ID TYPE_NAME
-------------------------------
0 CASH
1 CREDIT
我试过了:
select
TYPE_NAME,
sum(AMOUNT) as Amount,
sum(ServiceCharge) as SC
from
TENDER
left join
TYPE on TYPE.TYPE_ID = TENDER.TYPE_ID
left join
ITEM on ITEM.ITEM_ID = TENDER.ITEM_ID
group by
TYPE_NAME
但服务费用的结果已经重复,如
TYPE_NAME AMOUNT SC
-------------------------------
CASH 650 100
CREDIT 500 100
注意:服务费用计算为* 10
答案 0 :(得分:1)
可能是这样的:
select TYPE_NAME, sum(AMOUNT) as Amount,
sum(ServiceCharge)/ (COUNT(*) OVER (PARTITION BY TENDER.ITEM_ID) ) as SC
from TENDER
LEFT JOIN TYPE ON TYPE.TYPE_ID = TENDER.TYPE_ID
LEFT JOIN ITEM ON ITEM.ITEM_ID = TENDER.ITEM_ID
GROUP BY TYPE_NAME, TENDER.ITEM_ID;
答案 1 :(得分:1)
由于service charge
是amount
的10%,因此您不需要join
到item
表。相反,只需将sum(amount)
乘以.1:
select TYPE_NAME, sum(AMOUNT) as Amount, sum(AMOUNT) * .1 as SC
from TENDER
LEFT JOIN TYPE ON TYPE.TYPE_ID = TENDER.TYPE_ID
GROUP BY TYPE_NAME
导致:
type_name Amount SC
Cash 600 60
Credit 500 50
答案 2 :(得分:0)
我怀疑你想要这个:
select ITEM.ITEM_ID, ServiceCharge,
SUM(CASE WHEN TYPE_NAME = 'CASH' THEN Amount END) as Cash,
SUM(CASE WHEN TYPE_NAME = 'CREDIT' THEN Amount END) as Credit
from TENDER LEFT JOIN
TYPE
ON TYPE.TYPE_ID = TENDER.TYPE_ID LEFT JOIN
ITEM
ON ITEM.ITEM_ID = TENDER.ITEM_ID
GROUP BY ITEM.ITEM_ID, ServiceCharge;
这会将值放入列中,因此不会重复。
答案 3 :(得分:0)
我结合了Slava Murygin和sandeep rawat的答案,这给了我成功的销售成果。
想出了这个
;WITH SUMS AS (
select TYPE_NAME, AMOUNT as Amount,
sum(ServiceCharge)/ (COUNT(*) OVER (PARTITION BY TENDER.ITEM_ID) ) as SC
from TENDER
LEFT JOIN TYPE ON TYPE.TYPE_ID = TENDER.TYPE_ID
LEFT JOIN ITEM ON ITEM.ITEM_ID = TENDER.ITEM_ID
GROUP BY TYPE_NAME, TENDER.ITEM_ID, AMOUNT
)
Select Type_Name , Amount, Tender.ITEM_ID
From Sums
Group by TYPE_NAME
谢谢!
答案 4 :(得分:-1)
这对你有用吗?请根据您的方便更改列名称
SELECT
tender.item,typename,SUM(amount)as amount, SUM(Service_Charge/cntItem) as servercharge
FROM
woddb.TENDER_Table as Tender
INNER JOIN
(SELECT item, count(item) as cntItem FROM woddb.Tender_Table GROUP BY ITEM) as cntTable
ON
Tender.item = cntTable.Item
LEFT JOIN
woddb.TYPE_Table as TYPETable
ON
TYPETable.TYPEID = Tender.TYPEID
LEFT JOIN
woddb.ITEM_table as ITEMtable
ON
ITEMtable.ITEM = Tender.ITEM
GROUP BY
tender.item,typename