SQl销售交易

时间:2017-12-31 19:46:45

标签: sql sql-server group-by count sum

我有一张这样的桌子 一个。构件

memberid       name
MB001          NEERAJ RANA

湾销售标题

transaction_id   memberid
TR01             MB001
TR02             MB001

℃。销售细节

 transaction_id  qty
 TR01                  2
 TR01                  2
 TR02                  2

我的查询:

select member.name,
       count(salesheader.memberid), 
       sum(salesdetail.qty) 
from member inner join salesheader on member.memberid = salesheader.memberid 
     inner join salesdetail on salesheader.transaction_id = salesdetail.transaction_id 
group by member.name

我的输出

staffname           totaltransaction     totalqty
NEERAJ RANA         3                    6

我想像这样输出

staffname           totaltransaction     totalqty
NEERAJ RANA         2                    6

2 个答案:

答案 0 :(得分:2)

使用

COUNT(DISTINCT salesheader.memberid)代替COUNT(salesheader.memberid)

答案 1 :(得分:0)

您可以按名称加入使用加重功能计数和总和

select a.name, count(distinct b.transaction_id), sum(c.qty)
from Member
inner join sales_header b on a.memberid = b.memberid
inner join sales_detail c on b.transaction_id = c.transaction_id
group by a.name