在SQL中的Join情况下显示计数

时间:2018-09-22 05:59:25

标签: sql sql-server

我有这个查询,它的工作与我想要的一样好。但是我想添加一个计数列

sqlCustomerDetails = "Select Region,sum(debitamount) as Sales from (select region,debitamount from tblcustomerdetails where dateoftrans between '" & DateFrom & "' and '" & DateTo & "' and region like'%" & Me.txtRegion.Text & "%'" & _
        " union all select region,debitamount from tblupcustomerdetails where dateoftrans between '" & DateFrom & "' and '" & DateTo & "' and region like'%" & Me.txtRegion.Text & "%') t group by region order by sales desc"

好吧,在tblcustomerdetails和tblupcustomerdetails表中,有一列“ CustomerName”。

目前显示的结果如下。

Region - Sales

UK - 100,000

NY - 200,000

Germany - 500,000

以此类推,我想添加第三列,看起来像这样

Region - Sales - CustomerCount

UK - 100,000 - 10

NY - 200,000 - 20

Germany - 500,000 - 5

tblcustomerdetails和tblupcustomerdetails都具有以下列

CustomerName, Region, DebitAmount, DateOfTrans.

1 个答案:

答案 0 :(得分:1)

CustomerName添加到内部UNION查询中

select  region, debitamount, CustomerName
from    tblcustomerdetails

union all

select  region, debitamount, CustomerName
from    tblupcustomerdetails

在外部查询

Select Region, sum(debitamount) as Sales, COUNT(DISTINCT CustomerName) as CustomerCount

请勿更改GROUP BY

group by region
相关问题