Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

TSQL for retrieve all clients having invoices and not Expand / Collapse
Author
Message
Posted Monday, February 01, 2010 6:48 AM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Tuesday, March 05, 2013 10:34 AM
Points: 244, Visits: 480
Hello comunity

I have the following TSQL with a derived table, but i want to retrieve all clients (CL) independent that the sames have or not have invoices table (FT), the table (FI) is the lines of my invoice:

SELECT cl.nome,cl.vendnm AS 'Vendedor', SUM(myft.valor) AS 'Vendas'
FROM
(select ft.fdata,ft.no,ft.estab,ft.ftstamp,ft.tipodoc,
sum(fi.etiliquido) AS 'Valor'
FROM ft (nolock) inner join fi (nolock) on fi.ftstamp = ft.ftstamp
where fi.stns = 0
GROUP BY ft.ftstamp,ft.no, ft.estab,ft.tipodoc,ft.fdata) AS Myft
right JOIN
cl ON cl.no=myft.no AND cl.estab = myft.estab
WHERE myft.tipodoc IN (1,3) AND myft.fdata BETWEEN '20090101' AND
'20091231'
GROUP BY cl.vendnm,cl.nome

The problem that this script cannot retrieve all clients, some with invoice an anothers without invoices.

Could someone give me an ideia.
Many thanks
Luis Santos



Post #857128
Posted Monday, February 01, 2010 7:14 AM


SSC-Insane

SSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-InsaneSSC-Insane

Group: General Forum Members
Last Login: Today @ 6:38 PM
Points: 21,832, Visits: 27,852
Your where clause effectively turns your outer join into an inner join. Try the following query:

with Myft as (
select
ft.fdata,
ft.no,
ft.estab,
ft.ftstamp,
ft.tipodoc,
sum(fi.etiliquido) AS 'Valor'
FROM
ft
inner join fi
on (fi.ftstamp = ft.ftstamp)
where
fi.stns = 0
GROUP BY
ft.ftstamp,
ft.no,
ft.estab,
ft.tipodoc,
ft.fdata
)
SELECT
cl.nome,
cl.vendnm AS 'Vendedor',
SUM(myft.valor) AS 'Vendas'
FROM
cl
left outer join Myft
ON (cl.no = myft.no
AND cl.estab = myft.estab
AND myft.tipodoc IN (1,3)
AND myft.fdata BETWEEN '20090101' AND '20091231'
)
GROUP BY
cl.vendnm,
cl.nome;




Lynn Pettis

For better assistance in answering your questions, click here
For tips to get better help with Performance Problems, click here
For Running Totals and its variations, click here or when working with partitioned tables
For more about Tally Tables, click here
For more about Cross Tabs and Pivots, click here and here
Managing Transaction Logs

SQL Musings from the Desert Fountain Valley SQL (My Mirror Blog)
Post #857158
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse