Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding Group Columns

Status
Not open for further replies.
Mar 20, 2009
102
US
I have the below query:


DECLARE @StartDate datetime
SET @StartDate = '2009-7-27'
DECLARE @EndDate datetime
SET @EndDate = '2009-8-02'

select count (distinct employeeid), busunitdesc
from invinvoicedetail inv
inner join invinvoiceheader b on b.invoiceid = inv.invoiceid
inner join ssbusunit u on u.busunitid = inv.busunit
where b.invoicedate between @StartDate and @EndDate Group by busunitdesc

Which returns these results:

498 HR Solutions
1020 HR Solutions RTI

My ultimate goal is to get the total to add up to 1,518? If I do a distinct count without grouping, it returns 1,513 because there are 5 employees that are part of both groupings. How can I get a sum of 1,518?

Thanks a bunch
 
Something like the following?
Code:
select count (distinct employeeid), busunitdesc
from invinvoicedetail inv
inner join invinvoiceheader b on b.invoiceid = inv.invoiceid
inner join ssbusunit u on u.busunitid = inv.busunit
where b.invoicedate between @StartDate and @EndDate Group by busunitdesc

UNION ALL


select count (distinct employeeid), 'Total' AS busunitdesc
from invinvoicedetail inv
inner join invinvoiceheader b on b.invoiceid = inv.invoiceid
inner join ssbusunit u on u.busunitid = inv.busunit
where b.invoicedate between @StartDate and @EndDate
 
That doesn't give me the correct answer of 1518, it still gives me 1513 because the total is counting distinct employeeid?
 
Remove Distinct then and just do select count(*) as Total_Employees
 
What you want as a result?
Code:
DECLARE @StartDate datetime,
        @EndDate datetime
SET @StartDate = '20090727'
SET @EndDate   = '20090802'

SELECT SUM(DistCount) AS DistCount
FROM(
select count (distinct employeeid) DistCount, busunitdesc
from invinvoicedetail inv
inner join invinvoiceheader b on b.invoiceid = inv.invoiceid
inner join ssbusunit u on u.busunitid = inv.busunit
where b.invoicedate between @StartDate and @EndDate
Group by busunitdesc) Tbl1
?????


Borislav Borissov
VFP9 SP2, SQL Server 2000/2005.
 
if it is SQL 2005, use CTE

Code:
with Detail(empcount,busunitdesc)
as
(
select count (distinct employeeid), busunitdesc
from invinvoicedetail inv 
inner join invinvoiceheader b on b.invoiceid = inv.invoiceid 
inner join ssbusunit u on u.busunitid = inv.busunit
where b.invoicedate between @StartDate and @EndDate Group by busunitdesc
)
select empcount,
       busunitdesc, 
       (select sum(empcount) from Detail) TotEmpCount
from   Detail;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top