Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Tables:
Country table
District table
Sales table

Query:
I want to retrieve the districts which has no sales.

My query:
SQL
Select countyid, districtid, sales
From country c, district d, sales s
Where c. countryid  =d.districtid
And d.districtid = s. Salesid 
Where salesid not in ()
Group by countryid


What I have tried:

I’m not sure what syntax should I use to do this.
Posted
Updated 12-Jul-22 10:58am
v2
Comments
[no name] 11-Jul-22 19:05pm    
(1) Group by country, district and sales (2) then group (original data) by country, district (3) report set 2 NOT IN set 1.

The simplest option would probably be a NOT EXISTS clause:
SQL
SELECT
    d.districtid,
    c.countryid
FROM
    district As d
    INNER JOIN country As C
    ON c.countryid = d.countryid
WHERE
    Not Exists
    (
        SELECT 1
        FROM sales As s
        WHERE s.districtid = d.districtid
    )
;
Joins (SQL Server) - SQL Server | Microsoft Docs[^]
EXISTS (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 
Comments
Sql-beginner 12-Jul-22 8:34am    
@richard I executed the query and got empty results set. I want to display countryid, districtid and sales in select statement and retrieve only the results set which has no sales.
Richard Deeming 12-Jul-22 9:42am    
If you got empty results, then there are no matching rows in your data. You need to examine your data to find out why.

We can't do that for you, since we don't have access to your database.
Sql-beginner 12-Jul-22 11:11am    
@Richard, I did the joins right now and I’m getting the query results srt. But takes 11 seconds to load the data. Is there a way to tune this?
Richard Deeming 12-Jul-22 11:13am    
Probably. But since we can't see your tables, your indexes, your data, or your execution plan, we can't tell you how.

You could try sharing the execution plan via Paste The Plan - Brent Ozar Unlimited®[^], in case there's anything obviously wrong.
Sql-beginner 12-Jul-22 11:33am    
Select d.district, d.districtname, c.countryid
From district as d
Inner join Country as c
On c.countryid = d.countryid
Where not exists (
Select 1
From sales as s
Where s.districtid = d.districtid)
I'd suggest that you start by looking at SQL Joins[^] - they combine related data together into a single query.

And what do you think this clause does?
SQL
WHERE salesid NOT IN ()
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900