sql - Multiple subqueries when combined return too many results -
background
i have merged 2 long lists of financial transactions (one each of 2 companies) single table (actually dataview reasons not important here). these 2 companies did business lots of customers. want query returns total number of financial transactions each company had each customer.
for example:
customer company company b customer x 10 0 customer y 15 26 customer z 0 71 hence each customer has dealt @ least 1 company, , possibly both companies.
so far query has got far . . .
select v.[company], v. [analysisname], s1.cmttrans, s2.cfltrans vmaincusttrans v left join (select [analysisname], count([analysisname]) cmttrans vmaincusttrans [company] = 'money' group [analysisname]) s1 on v.[analysisname] = s1.[analysisname] left join (select [analysisname], count([analysisname]) cfltrans vmaincusttrans [company] = 'forex' group [analysisname]) s2 on v.[analysisname] = s2.[analysisname] order v.[company], v.[analysisname] now sub query (s1) returns 89 customers sub query (s2) returns 37 customers yet whole query returns 18,989 lines there should between 89 , 126 (i.e. 89 + 37) lines, depending on how overlap there between company , company b
could kindly point out wrong query , how produce results want; namely list of customers, 2 counts iro of number of transactions have had each of 2 customers.
if i've got right (customer = analysisname)it should looks like:
select v. [analysisname], sum(case when [company] = 'money' 1 else 0 end) cmttrans, sum(case when [company] = 'forex' 1 else 0 end) cfltrans vmaincusttrans v group v.[analysisname] order v.[analysisname]
Comments
Post a Comment