Microsoft Access SQL query count distinct - sql

I am trying to create a queries in MS Access SQL that performs two separate counts function and have drafted the below code:
SELECT DISTINCT A.Name, Count(A.Name) AS X, Count(b.Address) AS Y
FROM PEOPLE AS A INNER JOIN PEOPLE Sub AS b ON A.PID = b.PID
GROUP BY A.Nam
The problem with this query is that both count functions provide a total count of the number of address for each name and I want the first count function to provide a count of names, therefore I would be grateful if someone could advise how I amend this code to change the first count function to a count distinct
Thanks
Nick

Your Query is wrong - GROUP BY must have A.Name - i think it´s an error by copying.
Otherwise change this. What happens if you do it without DISTINCT? Try it with SUM not with COUNT.

Distinct in your query is obsolete because of the GROUP BY clause.
Furthermore it is not clear if your 'People sub' refers to another table or is a self-join. The following code should work:
SELECT P.Name
, COUNT(P.*) AS X
, COUNT(DISTINCT A.Address) AS Y
FROM PEOPLE AS P
INNER JOIN ADDRESS AS A ON A.PID = P.PID
GROUP BY P.Name

Related

How to count the number of occurrences in a self-referencing column?

I am new to SQL and I've been struggling with this example for quite a while now.
I have this table:
So, what is asked from me is to produce a count of the number of recommendations each member has made. Order by number of recommendations. The final result should look something like this:
I really am confused, since the values of column recommendedby is actually the id of the member. I don't know how to "recognize" them as id and not just some values, count how many recommendations each member has and "connect" them to memid column to get to needed result.
So far I managed to do this:
SELECT COUNT(recommendedby)
FROM members
GROUP BY recommendedby
But I'm stuck now. I get a counted number of recommendations for each id, but it's not connected to actual id. This is my result.
I think this is what you're looking for:
select "id"
, (select count(1)
from "members"
where "recommendedby" = m."id")
from "members" m
Although using subqueries are not very popular and can cause serious performance issues, this is imho the easiest way to learn what you're doing.
You should use a self-join for this:
SELECT m.id,
count(r.id) AS recommendations
FROM members AS m
LEFT JOIN members AS r
ON r.recommendedby = m.id
GROUP BY m.id
ORDER BY recommendations;
The left join will make r.id be NULL for members that made no recommendation, and count won't count such NULL values.
There are two ways you can go with.
Join + Group By
This is pretty simple, all you need to do is put the query you made as SubQuery and Join your table with that.
SELECT members.*, rec.recommendations
FROM members
LEFT JOIN (
SELECT COUNT(recommendedby) recommendations, recommendedby
FROM members
GROUP BY recommendedby
) rec ON rec.recommendedby = members.id
Lateral
SELECT m1.*, rec.recommendations
FROM members m1,
LATERAL (
SELECT COUNT(recommendedby) recommendations
FROM members m2
WHERE m1.id = m2.id
)
Hope this can help.

syntax error in Hive Query

I am trying to answer this question
Of the right-handed batters who were born in October and died in
2011, which one had the most hits in his career?
My attempt to get the query, Please ignore the total, it supposed to for sums for b.hits, dont know how to alias it.
SELECT n.id, n.bmonth, n.dyear,n.bats, SUM(b.hits) FROM master n
JOIN (SELECT b.id , b.hits FROM batting GROUP BY id) o
WHERE n.bmonth == 10 AND n.dyear == 2011) x
ON x.id=n.id
ORDER BY total DESC;
Incase anyone needs the schema of the two tables used, look below.
INSERT OVERWRITE DIRECTORY '/home/hduser/hivetest/answer4'
SELECT n.id, n.bmonth, n.dyear,n.bats, SUM(b.hits) FROM master n
JOIN (SELECT b.id , b.hits FROM batting GROUP BY id) o
WHERE n.bmonth == 10 AND n.dyear == 2011) x
ON x.id=n.id
ORDER BY total DESC;
First, although Hive accepts ==, that doesn't mean you should use it. The standard SQL equality operator is simply =. There is no reason to use a synonym.
I suspect the problem is several things:
The lack of group by.
Mis-use of aggregation functions.
Missing aliases
SQL query clauses in the correct order
Unbalanced parentheses
In other words, the query is just a mess. You need to review the basics of query syntax. Does this work?
SELECT m.id, m.bmonth, m.dyear, m.bats, b.hits as total
FROM master m JOIN
(SELECT b.id, SUM(b.hits) as hits
FROM batting b
GROUP BY id
) b
ON b.id = m.id
WHERE m.bmonth = 10 AND m.dyear = 2011
ORDER BY total DESC;

GROUP BY not working in left join query

I m trying to use group by clause in left join sql query and it is not working.
Please help me out, thanks in advance.
SELECT Cust_Mst_Det.Cust_Hd_Code,
Cust_Mst_Det.First_Name,
SL_HEAD20152016.vouch_date AS invoice_2,
SL_HEAD20142015.vouch_date AS invoice_1,
Cust_Mst_Hd.EMail
FROM Cust_Mst_Det
LEFT JOIN SL_HEAD20142015 ON Cust_Mst_Det.Cust_Hd_Code=SL_HEAD20142015.Member_Code
LEFT JOIN SL_HEAD20152016 ON Cust_Mst_Det.Cust_Hd_Code=SL_HEAD20152016.Member_Code
LEFT JOIN Cust_Mst_Hd ON Cust_Mst_Det.Cust_Hd_Code=Cust_Mst_Hd.Cust_Hd_Code
WHERE cust_mst_det.first_name!='NIL'
GROUP BY Cust_Mst_Det.Cust_Hd_Code
ORDER BY SL_HEAD20152016.vouch_date DESC,
SL_HEAD20142015.vouch_date
I'm not sure which DBMS you are using, but on an Oracle your query will not work at all.
First issue: The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns. You do not have any aggregating function in your SELECT statement (count, max, etc.)
Second issue: you must specify all columns from SELECT statement in your GROUP BY statement (excluding columns that represents results of aggregation).
As I said I don't know which DB is used by you, but those two points should be applicable for the most of SQL standards.
It appears that it is impossible to use an ORDER BY on a GROUP BY summarisation. My fundamental logic is flawed. I will need to run the following subquery.
ex :
SELECT p.*, pp.price
FROM products p
LEFT JOIN ( SELECT price FROM product_price ORDER BY date_updated DESC ) pp
ON p.product_id = pp.product_id GROUP BY p.product_id;
This will take a performance hit but as it is the same subquery for each row it shouldn't be too bad.

Self Join bringing too many records

I have this query to express a set of business rules.
To get the information I need, I tried joining the table on itself but that brings back many more records than are actually in the table. Below is the query I've tried. What am I doing wrong?
SELECT DISTINCT a.rep_id, a.rep_name, count(*) AS 'Single Practitioner'
FROM [SE_Violation_Detection] a inner join [SE_Violation_Detection] b
ON a.rep_id = b.rep_id and a.hcp_cid = b.hcp_cid
group by a.rep_id, a.rep_name
having count(*) >= 2
You can accomplish this with the having clause:
select a, b, count(*) c
from etc
group by a, b
having count(*) >= some number
I figured out a simpler way to get the information I need for one of the queries. The one above is still wrong.
--Rep violation for different HCP more than 5 times
select distinct rep_id,rep_name,count(distinct hcp_cid)
AS 'Multiple Practitioners'
from dbo.SE_Violation_Detection
group by rep_id,rep_name
having count(distinct hcp_cid)>4
order by count(distinct hcp_cid)

SQL query from an existing list

Sql newb so im trying to figure this out:
I pull a list of customer names that purchase a certain item:
select r.name
from records r
where r.item_purchased='apple'
Now I want to take that list of customers and pull the records for everything they have purchased, but I can't get past the errors. I've tried things like:
with customer_list as
(above)
select r.*
from records r
where r.name=customer_list
If you do want to use a CTE, this should work:
with customer_list as
(
select r.name
from records r
where r.item_purchased='apple'
)
select r.*
from records r
where r.name in (select name from customer_list)
The difference between this and a JOIN (e.g. Michael's solution) is the join will produce a different result if the same customer purchased an apple more than once.
I believe a self join should solve your problem:
select distinct r2.*
from records r
join records r2
on r2.name = r.name
where r.item_purchased='apple'
EDIT: Added a DISTINCT based on #a_horse_with_no_name's insight into the difference between the results, because I doubt the duplication caused by the self join would be the desired result.
Select * from records where name in (
select name
from records
where item_purchased='apple'
)