sql returning three time the same column - sql

I'm having troubles trying to select three times the user name.
I have a table
JOBS (id, id_student, id_professor, id_professor2)
This last column is optional, then sometimes NULL is set in its content. When that happens, the query doesn't return any rows. However, if id_professor2 is set, the query returns like I expect. How can I fix this?
SELECT
p.name as professor, s.name as student, s_p.name as second_professor
FROM
users as p
JOIN
jobs ON (p.id = jobs.id_professor)
JOIN
users as s ON (jobs.id_student = s.id)
JOIN
users as s_p ON (s_p.id = jobs.id_professor2)
WHERE
jobs.id = 2;
The job with id=2 has an second professor, so the query runs normally. But if a change for jobs.id=3 the query doesn't return anything.

Use a left outer join
SELECT p.name as professor, a.name as student, s_p.name as second_professor
FROM users as p
JOIN jobs ON(p.id = jobs.id_professor)
JOIN users as s ON(jobs.id_student = a.id)
left outer
JOIN users as c ON(c.id = jobs.id_professor2)
WHERE jobs.id = 2
;

Related

Fetch rows and count them in sqlserver

I wrote a stored procedure that join three tables to fetch province title from it's table. This is my code:
BEGIN
select TbProvince.title, count(TbProvince.title) as cnt
from TbProvince
where TbProvince.provinceId IN (select TbCustomerUser.provinceId
from TbCustomerUser INNER JOIN
TbDeals
on TbCustomerUser.UserId = TbDeals.sellerUserID
where TbDeals.buyerUserID = 1
)
group by TbProvince.title
end
Description: I have three tables for deals, customers and provinces. I want to retrieve province title and the count of that for customers that were sellers.
The above code have no problem, but only return 1 as a count. The number of customers is more than one.
Can anybody help me solve my problem?
Your query is filtering the rows of TbProvince and then aggregating that table -- and only that table.
Instead, you want to join the tables together to count the customers not the provinces. The query is much simpler to write and read if you use table aliases:
select p.Title, count(*)
from TbCustomerUser cu join
TbDeals d
on cu.UserId = d.sellerUserID join
TbProvince p
on p.provinceId = cu.provinceId
where d.buyerUserID = 1
group by p.Title;
You have to perform the JOIN with customer table. If you use semi join (expressed by IN construct in your case) then you avoid duplicates that are expected in your case.
SELECT TbProvince.title,
COUNT(TbProvince.title) AS cnt
FROM TbProvince
JOIN TbCustomerUser ON TbProvince.provinceId = TbCustomerUser.provinceId
JOIN TbDeals ON TbCustomerUser.UserId = TbDeals.sellerUserID
WHERE TbDeals.buyerUserID = 1
GROUP BY TbProvince.title;
It should be as simple as:
You won't need the subselect. Just join all three tables and you'll receive your desired result.
SELECT TbProvince.title,
count(TbProvince.title) as cnt
FROM TbProvince
INNER JOIN TbCustomerUser
ON TbProvince.provinceId = TbCustomerUser.provinceId
INNER JOIN TbDeals
ON TbCustomerUser.UserId = TbDeals.sellerUserID
AND TbDeals.buyerUserID = 1
GROUP BY TbProvince.title
Why did your solution not work?
You subselect will return a "list" of provinceIDs from TbCustomerUser combinated with TbDeals with your restriction TbDeals.buyerUserID = 1.
The outer select will now return all rows from TbProvince IN this list.
But it's not returning a row for each Customer who had a deal.
That's why you have to JOIN all three tables at once.

Left outer join with count, on 3 tables not returning all rows from left table

I have these 3 tables:
Areas - id, name
Persons - id, area_id
Special_Persons - id_person, date
I'd like to produce a list of all Areas, followed by a count of Special Persons in each area, including Areas with no Special Persons.
If I do a left join of Areas and Persons, like this:
select a.id as idArea, count(p.id) as count
from areas a
left join persons p on p.area_id = a.id
group by a.id;
This works just fine; Areas that have no Persons show up, and have a count of 0.
What I am not clear on is how to do the same thing with the special_persons table, which currently only has 2 entries, both in the same Area.
I have tried the following:
select a.id as idArea, count(sp.id_person) as count
from special_persons sp, areas a
left join persons p on p.area_id = a.id
where p.area_id = a.id
and sp.id_person = p.id
group by a.id;
And it only returns 1 row, with the Area that happens to have 2 Special Persons in it, and a count of 2.
To continue getting a list of all areas, do I need to use a sub-query? Another join? I'm not sure how to go about it.
You can add another left join to the Special_Persons table:
select a.id as idArea, count(p.id), count(sp.id_person)
from areas a
left join persons p on p.area_id = a.id
left join special_persons sp on sp.id_person = p.id
group by a.id;

SQL ecommerce database - getting count of products purchased by only one user

In my rails app I have a typical ecommerce schema inside a Postgres 9.6 database. Here's a simplified version of it:
users table
:name
products table
:name
shopping_carts table
:user_id
line_items table
:price
:qty
:product_id
:shopping_cart_id
I've got a working query to return the number of distinct products bought by each user:
SELECT COUNT(distinct p.*), u.name FROM products p
INNER JOIN line_items l ON p.id = l.product_id
INNER JOIN shopping_carts sc ON l.shopping_cart_id = sc.id
INNER JOIN users u ON sc.user_id = u.id
GROUP BY u.name
But I also want a count of products for each user that only that particular user has purchased. A possible method for this in Ruby (once everything was set up with ActiveRecord) might look something like:
def unique_prod(user)
user.products.select { |p| p.users.length == 1 }.count
end
But how to do it in SQL? I think I need to do it using two counts - one for the number of different user_ids in a given product's shopping_carts (let's call this count user_count), and then a count of products for which user_count = 1. I'm having trouble incorporating the multiple COUNT and GROUP BY statements in working fashion. Any suggestions?
To do it all in one query:
SELECT scl.user_id, u.name, ct_dist_prod, ct_dist_prod_exclusive
FROM (
SELECT sc.user_id
, count(DISTINCT l.product_id) AS ct_dist_prod
, count(DISTINCT l.product_id)
FILTER (WHERE NOT EXISTS (
SELECT 1
FROM shopping_carts sc1
JOIN line_items l1 ON l1.shopping_cart_id = sc1.id
WHERE l1.product_id = l.product_id
AND sc1.user_id <> sc.user_id)) AS ct_dist_prod_exclusive
FROM shopping_carts sc
JOIN line_items l ON l.shopping_cart_id = sc.id
GROUP BY 1
) scl
JOIN users u ON u.id = scl.user_id;
I added the user_id to the result, because I cannot assume that name is defined unique (which would make your original query slightly incorrect).
The aggregate FILTER clause requires Postgres 9.4 or later:
How can I simplify this game statistics query?
How?
Assuming referential integrity enforced by a FK constraint, you do not need to join to the table products at all for this query.
Neither, at first, to the users table. The basic query boils down to:
SELECT sc.user_id, count(DISTINCT l.product_id)
FROM shopping_carts sc
JOIN line_items l ON l.shopping_cart_id = sc.id
GROUP BY 1;
Add the 2nd count to this cheaper query, where all rows with products are excluded for which another row with the same product and a different user exists (i.e. bought by a different user, too).
Then join to users to add the name. Cheaper.
Computing only the exclusive count is simpler. Example:
SELECT sc.user_id, count(DISTINCT l.product_id) AS ct_dist_prod_exclusive
FROM shopping_carts sc
JOIN line_items l ON l.shopping_cart_id = sc.id
LEFT JOIN (
shopping_carts sc1
JOIN line_items l1 ON l1.shopping_cart_id = sc1.id
) ON l1.product_id = l.product_id
AND sc1.user_id <> sc.user_id
WHERE l1.product_id IS NULL
GROUP BY 1;
Note the essential parentheses.
Related:
Select rows which are not present in other table
Or (in response to your comment):
SELECT user_id, count(*) AS ct_dist_prod_exclusive
FROM (
SELECT max(user_id) AS user_id, l1.product_id
FROM line_items l1
INNER JOIN shopping_carts sc1 ON l.shopping_cart_id = sc1.id
GROUP BY l1.product_id
HAVING COUNT(DISTINCT sc1.user_id) = 1 -- DISTINCT!
) p1
GROUP BY user_id;
HAVING COUNT(DISTINCT sc1.user_id) = 1 because
products purchased by only one user
allows the product to be bought by the same user multiple times.

i want to modify this SQL statement to return only distinct rows of a column

select
picks.`fbid`,
picks.`time`,
categories.`name` as cname,
options.`name` as oname,
users.`name`
from
picks
left join categories
on (categories.`id` = picks.`cid`)
left join options
on (options.`id` = picks.oid)
left join users
on (users.fbid = picks.`fbid`)
order by
time desc
that query returns a result that like:
my question is.... I would like to modify the query to select only DISTINCT fbid's. (perhaps the first row only sorted by time)
can someone help with this?
select
p2.fbid,
p2.time,
c.`name` as cname,
o.`name` as oname,
u.`name`
from
( select p1.fbid,
min( p1.time ) FirstTimePerID
from picks p1
group by p1.fbid ) as FirstPerID
JOIN Picks p2
on FirstPerID.fbid = p2.fbid
AND FirstPerID.FirstTimePerID = p2.time
LEFT JOIN Categories c
on p2.cid = c.id
LEFT JOIN Options o
on p2.oid = o.id
LEFT JOIN Users u
on p2.fbid = u.fbid
order by
time desc
I don't know why you originally had LEFT JOINs, as it appears that all picks must be associated with a valid category, option and user... I would then remove the left, and change them to INNER joins instead.
The first inner query grabs for each fbid, the FIRST entry time which will result in a single entity for the FBID. From that, it re-joins to the picks table for the same ID and timeslot... then continues for the rest of the category, options, users join criteria of that single entry.
2 options, you could write a group by clause.
Or you could write a nested query joined back to itself to get pertinent info.
Nested aliased table:
SELECT
n.fBids
FROM
MyTable t
INNER JOIN
(SELECT DISTINCT fBids
FROM MyTable) n
ON n.ID = t.ID
Or group by option
SELECT fBId from MyTable
GROUP BY fBID
select picks.`fbid`, picks.`time`, categories.`name` as cname,
options.`name` as oname, users.`name` from picks left join categories
on (categories.`id` = picks.`cid`) left join options on (options.`id` = picks.oid)
left join users on (users.fbid = picks.`fbid`)
order by time desc GROUP BY picks.`fbid`
select
picks.fbid,
MIN(picks.time) as first_time,
MAX(picks.time) as last_time
from
picks
group by
picks.fbid
order by
MIN(picks.time) desc
However, if you want only distinct fbid's you cannot display cname and other columns at the same time.

Need help with a simple Join

Oi
Right to the problem.
SELECT *,t.id AS threadid FROM threads t
LEFT JOIN players p on p.id = t.last_poster
WHERE t.boardid = $boardid
I have two fields in threads called posterid and lastposterid. Which are the IDs of the thread starter / last poster. What I want to do is to get their names from players table.
But how?
You just need to join to your players table twice, like this.
SELECT
threads.*,
starterPlayer.*,
lastPosterPlayer.*
FROM
threads
LEFT OUTER JOIN
players starterPlayer
ON
starterPlayer.id = threads.posterid
LEFT OUTER JOIN
players lastPosterPlayer
ON
lastPosterPlayer.id = threads.lastposterid
You can join to the same table twice and give the table a different alias.
This presumes that there always will be a first and last poster, if this is the case then you want an INNER JOIN rather than a LEFT JOIN, you will need to change the select statement to get the relevant fields.
SELECT t.id AS threadid, playerFirst.name AS FirstPoster, playerLast.name as LastPoster
FROM threads t
INNER JOIN
players playerFirst ON playerFirst.id = t.posterid
INNER JOIN
players playerLast ON playerLast.id = t.lastposterid
How about...
SELECT *,
(SELECT name
FROM players
WHERE players.id = threads.posterid) AS poster,
(SELECT name
FROM players
WHERE players.id = threads.lastposterid) AS last_poster
FROM threads;