MySQL: get count value in joins and if else - mysql

In My application I want to display all my friends and no of cheque given and received
Table Transaction Table Friends
---------------------------- -----------------------------
id given_id rev_id amt id who_id whom_id who_name
----------------------------- -------------------------------
1 2 1 1k 1 1 2 sss
2 2 3 1k 2 3 2 fff
3. 3 2 2k 3 4 1 eee
4 1 2 2k 4 2 1 iii
----------------------------- ------------------------------
Result whom_id=2 name=iii -> Friends (sss,fff)
=> sss gives totally 1 cheque and
sss receives totally 1 cheque and
fff gives 1 cheque and
fff receives 1 cheque and
I tried This one..
SELECT
p.who_id,
p.who_name,
COUNT( r1.give_id ) ,
COUNT( r1.rec_id )
FROM
friends p
LEFT JOIN Transaction r1
ON p.who_id = r1.give_id OR p.who_id = r1.rec_id
WHERE
p.whom_id = 1
GROUP BY p.who_id
Please provide me the best way to do this....

You can do it like this
SELECT
f.who_name,
count(t.given_id) GivenTotal,
count(lt.rev_id) as RecievedTotal
from friends as f
left join transaction as t
on t.given_id = f.who_id
left join transaction as lt
on lt.rev_id = f.who_id
where f.whom_id = 2
group by t.given_id
Demo
Output
who_name | GivenTotal | RecievedTotal
----------------------------------
sss | 1 | 1
fff | 1 | 1

try this,
select
id,
count(given_id) as given,
count(rev_id) as reveive
from Friends
GROUP BY id;
and if you whant the difference between the two amounts try this
select
id,
count(given_id) as given,
count(rev_id) as reveive,
given-receive as diff
from Friends
GROUP BY id;

You can use HAVING with group by ,
instead
WHERE p.whom_id = 1

There are two ways to do this, both involve joining on the Transactions table twice.
You can use subqueries:
SELECT f.who_id,
f.who_name,
t1.TotalGiven,
t2.TotalRev
FROM friends f
LEFT JOIN
(
select count(t.given_id) TotalGiven, t.given_id
from Transactions t
group by t.given_id
) t1
ON f.who_id = t1.given_id
LEFT JOIN
(
select count(t.rev_id) TotalRev, t.rev_id
from Transactions t
group by t.rev_id
) t2
ON f.who_id = t2.rev_id
where f.whom_id = 2;
See SQL Fiddle with Demo.
Or you can just use a join with no subquery:
select f.who_id,
f.who_name,
count(t1.given_id) TotalGiven,
count(t2.rev_id) TotalRev
FROM friends f
LEFT JOIN Transactions t1
ON f.who_id = t1.given_id
LEFT JOIN Transactions t2
ON f.who_id = t2.rev_id
where f.whom_id = 2
group by f.who_id, f.who_name
See SQL Fiddle with Demo

Finally I got the answer,
SELECT
p.who_id, p.who_name, COUNT( r1.give_id ) , COUNT( r2.rec_id )
FROM
friends p
LEFT JOIN Transaction r1 ON p.who_id = r1.give_id
LEFT JOIN Transaction r2 on p.who_id = r2.rec_id
WHERE
p.whom_id = 1
GROUP BY p.who_id

Related

MySQL Query To find Trains between two stations

My Train Details table,
Table Name- traindetailtb
Id Train_Number Train_Name From To
1 27658 Venad Express ABC XYZ
2 27659 Venad Express XYZ ABC
and my Train Days Table,
Table Name- traindaystb
Id Train_Number Days
1 27658 Sunday
2 27658 Wednesday
3 27659 Saturday
4 27659 Friday
and this my Train Schedule Table,
Table Name- scheduletb
Id Train_Number Station Time
1 27658 ABC 09:00am
2 27658 CDE 10:00am
3 27658 XYZ 11:00am
4 27659 XYZ 12:00pm
5 27659 CDE 01:00pm
6 27659 ABC 02:00pm
There will be two input, From and To
I need a query that gives all Trains(ie,Train_Number,Train_Name,Days) between the given stations
For eg:
For input From- CDE To-XYZ ---->
output will be-- 27658 Venad Express S W
and For input From- XYZ To-CDE ---->
output will be-- 27659 Venad Express M T
Can anyone Please help me to do this.
Are you looking for something like this?
SELECT q.train_number, MAX(t.train_name) train_name, GROUP_CONCAT(LEFT(d.days, 1)) days
FROM
(
SELECT s.train_number
FROM scheduletb s JOIN scheduletb e
ON s.train_number = e.train_number
WHERE s.station = 'CDE' -- from
AND e.station = 'XYZ' -- to
AND s.id < e.id
) q JOIN traindaystb d
ON q.train_number = d.train_number JOIN traindetailtb t
ON q.train_number = t.train_number
GROUP BY q.train_number
Output for CDE -> XYZ:
| TRAIN_NUMBER | TRAIN_NAME | DAYS |
|--------------|---------------|------|
| 27658 | Venad Express | S,W |
Output for XYZ -> CDE:
| TRAIN_NUMBER | TRAIN_NAME | DAYS |
|--------------|---------------|------|
| 27659 | Venad Express | S,F |
Here is SQLFiddle demo
You can try somthing like this:-
SELECT A.Train_number, A.Train_name, C.days
FROM traindetailtb A, traindaystb B, scheduletb C
WHERE C.Train_Number = A.Train_Number
AND A.Train_Number = B.Train_Number
AND FROM = 'ABC' AND TO = 'XYZ';
This might help you.
Try this
SELECT t.Train_Number,t.Train_Name,d.Days
from traindetailtb t,traindaystb d
WHERE
t.Train_Number=d.Train_Number AND From='ABC' AND To='XYZ';
and just read the input and put it into the from=' ' and to=' ';
this single query will return both the output?
i suggest as follow :
select
traindetailtb.Train_Number,
traindetailtb.Train_Name,
traindetailtb.From,
traindetailtb.To,
tranddaystb.Days,
scheduletb.Time
From
traindetailtb
join trandaystb on
traindetailtb.Train_Number=traindaystb.Train_Number
join scheduletb on
traindetailtb.Train_Number=scheduletb.Train_Number and
traindetailtb.From=scheduletb.From
where
traindetailtb.From=$inputFrom
and
traindetailtb.To=$inputTo
Using a self join you can do this, assuming that the Time is really a time field
SELECT a.Train_Number, d.Train_Name, GROUP_CONCAT(e.Days)
FROM scheduletb a
INNER JOIN scheduletb b
ON a.Train_Number = b.Train_Number
AND b.Time > a.Time
INNER JOIN traindetailtb d
ON a.Train_Number = d.Train_Number
INNER JOIN traindaystb e
ON a.Train_Number = e.Train_Number
WHERE a.Station = 'CDE'
AND b.Station = 'XYZ'
GROUP BY a.Train_Number, d.Train_Name
assuming that you have a real time field for the time
If you wanted only the trains that went directly from CDE to XYZ with no intermediate stations you could add a LEFT OUTER JOIN to the table looking for stations with a time between the other 2:-
SELECT a.Train_Number, d.Train_Name, GROUP_CONCAT(e.Days)
FROM scheduletb a
INNER JOIN scheduletb b
ON a.Train_Number = b.Train_Number
AND b.Time > a.Time
LEFT OUTER JOIN scheduletb c
ON a.Train_Number = c.Train_Number
AND c.Time > a.Time
AND c.Time < b.Time
INNER JOIN traindetailtb d
ON a.Train_Number = d.Train_Number
INNER JOIN traindaystb e
ON a.Train_Number = e.Train_Number
WHERE a.Station = 'CDE'
AND b.Station = 'XYZ'
AND c.Station IS NULL
GROUP BY a.Train_Number, d.Train_Name
If you want to visualize the days in one single cell instead of spread into multiple rows, use GROUP_CONCAT, which acts as a aggregator-function.
select tde.train_number, tde.train_name, GROUP_CONCAT(tda.days, ",") as days
from traindetailtb tde
join traindaystb tda on tda.train_number=tde.train_number
where tde.from = $user_input_from
and tde.to = $user_input_to
group by tde.train_number, tde.train_name

Select inner join with n_m table

I have three tables as following:
USERS TABLE
id_user| name |
---------------
1 | ...
2 | ...
SERVICES TABLE
id_service | name |
-------------------
1 | ...
2 | ...
3 | ...
USER_SERVICES TABLE (n-m)
id_user | id_service
--------------------
1 | 1
1 | 2
2 | 1
And I need to do a SELECT starting from "SELECT * FROM users" and then, getting the users by services. Ex. I need to get every user with services = 1 and services = 2 (and maybe he has other more services, but 1 and 2 for sure).
I did the following:
SELECT *
FROM `users`
INNER JOIN user_services ON users.id_user = user_services.id_user
WHERE id_service=1 AND id_service=2
But this, of course dont works since there is not a single record matching service = 1 and service = 2.
What can I do?
Add an extra join for the other service you want to check:-
SELECT *
FROM `users`
INNER JOIN user_services us1 ON users.id_user = us1.id_user AND us1.id_service=1
INNER JOIN user_services us2 ON users.id_user = us2.id_user AND us2.id_service=2
select t.*,
(select count(*) from user_services where id_user = t.id_user) how_much
from users t;
Is this what you want???
It shows the data of the users and how much services are in the services table. Other possibility is this:
select t.*,
(case when (select count(*)
from user_services where id_user = 1) > 0
then 'service1'
else 'null'
end) has_service_1
from users t;
The problem with this select is that you have to repeat this case...end as much times as id_services you have, so it doesn't make sense if the number of services is increasing over time. On the contrary, if it is a somewhat fixed number, and it is not a big number, this could be a solution.

How to get 2 results from 3 tables with 1 mysql syntax

I have 3 tables like this
soft_id soft_name
1 Office
pu_id soft_id pu_quantity
1 1 10
2 1 20
3 1 30
own_id soft_id owner
1 1 Peter
2 1 Tommy
3 1 David
How can I have a result like this in one single mysql query
soft_id soft_name sum(pu_quantity) count(owner)
1 Office 60 3
Try this:
SELECT a.soft_id,
a.soft_name,
b.p_cnt AS quantity,
c.o_cnt AS owner_count
FROM soft a
INNER JOIN
(SELECT soft_id, SUM(pu_quantity) AS p_cnt FROM product GROUP BY soft_id
) b
ON a.soft_id = b.soft_id
INNER JOIN
(SELECT soft_id, COUNT(*) AS o_cnt FROM owner GROUP BY soft_id
) c
ON b.soft_id = c.soft_id
GROUP BY a.soft_id,
a.soft_name
SQLFiddle
Note: assuming that the table names are soft, product and owner respectively.
Try this
SELECT S.soft_id,S.soft_name,P.sum(pu_quantity),O.count(owner)
FROM Soft S INNER JOIN Product P ON S.soft_id = P.soft_id
Inner JOIN Owner O = P.soft_id = O.soft_id
Group By S.soft_id,P.soft_id,O.soft_id,S.soft_name

Select from one table but filtering other two

Let's say i've got this database:
book
| idBook | name |
|--------|----------|
| 1 |Book#1 |
category
| idCateg| category |
|--------|----------|
| 1 |Adventures|
| 2 |Science F.|
book_categ
| id | idBook | idCateg | DATA |
|--------|--------|----------|--------|
| 1 | 1 | 1 | (null) |
| 2 | 1 | 2 | (null) |
I'm trying to select only the books which are in category 1 AND category 2 something like this
SELECT book.* FROM book,book_categ
WHERE book_categ.idCateg = 1 AND book_categ.idCateg = 2
Obviously, this giving 0 results becouse each row has only one idCateg it does work width OR but the results are not what I need. I've also tried to use a join, but I just can't get the results I expect.
Here it's the SQLFiddle of my current project, with my current DB, the data at the begining is just a sample. SQLFiddle
Any help will be really appreciated.
Solution using EXISTS:
select *
from book b
where exists (select 'x'
from book_categ x
where x.idbook = b.idbook
and x.idcateg = 1)
and exists (select 'x'
from book_categ x
where x.idbook = b.idbook
and x.idcateg = 2)
Solution using join with an inline view:
select *
from book b
join (select idbook
from book_categ
where idcateg in (1, 2)
group by idbook
having count(*) = 2) x
on b.idbook = x.idbook
You could try using ALL instead of IN (if you only want values that match all criteria to be returned):
SELECT book.*
FROM book, book_categ
WHERE book_categ.idCateg = ALL(1 , 2)
One way to get the result is to do join to the book_categ table twice, something like
SELECT b.*
FROM book b
JOIN book_categ c1
ON c1.book_id = b.id
AND c1.idCateg = 1
JOIN book_categ c2
ON c2.book_id = b.id
AND c2.idCateg = 2
This assumes that (book_id, idCateg) is constrained to be unique in the book_categ table. If it isn't unique, then this query can return duplicate rows. Adding a GROUP BY clause or the DISTINCT keyword will eliminate any generated duplicates.
There are several other queries that can get generate the same result.
For example, another approach to finding book_id that are in two categories is to get all the rows with idCateg values of 1 or 2, and then GROUP BY book_id and get a count of DISTINCT values...
SELECT b.*
FROM book b
JOIN ( SELECT d.book_id
FROM book_categ d
WHERE d.idCateg IN (1,2)
GROUP BY d.book_id
HAVING COUNT(DISTINCT d.idCateg) = 2
) c
ON c.book_id = b.id

difficulties getting a 3 table join to return expected results

I'm having some difficulty getting to the bottom of this sql query.
Tables:
--Tickets-- --Finance-- --Access--
id_tickets id_finance id_access
name_tickets id_event id_event
cat_tickets id_tickets id_tickets
sold_finance scan_access
Finance and Access both contain a row for multiple of each ticket type as listed in tickets.
and I'm trying to get:
cat_tickets | total_sold | total_scan
-------------------------------------
single | 3043 | 2571
season | 481 | 292
comp | 114 | 75
-------------------------------------
total | 3638 | 2938
The closest I've been to the result I've used:
SELECT tickets.cat_tickets, COALESCE(SUM(finance.sold_finance), 0) AS total_sold, COALESCE(SUM(access.scan_access), 0) AS total_scan
FROM finance INNER JOIN tickets ON finance.id_tickets = tickets.id_tickets
INNER JOIN access ON access.id_tickets = tickets.id_tickets
WHERE access.id_event = 235 AND finance.id_event = access.id_event
GROUP BY tickets.cat_tickets
ORDER BY tickets.cat_tickets DESC
but that just returns:
cat_tickets | total_sold | total_scan
-------------------------------------
single | 4945 | 4437
season | 954 | 599
comp | 342 | 375
-------------------------------------
total | 6241 | 5411
Any ideas where I could be going wrong?
Thanks!
The problem is the relation between access and finance tables, you have to join them. Even if you LEFT JOIN the table the predicate finance.id_event = access.id_event will make it INNER JOIN. As a work around, use UNION like this:
SELECT
tickets.cat_tickets,
SUM(CASE WHEN a.Type = 'f' THEN num ELSE 0 END) AS total_sold,
SUM(CASE WHEN a.Type = 'a' THEN num ELSE 0 END) AS total_scan
FROM tickets
LEFT JOIN
(
SELECT 'f' Type, id_tickets, sold_finance num
FROM finance f
WHERE id_event = 1
UNION ALL
SELECT 'a', id_tickets, scan_access
FROM access
WHERE id_event = 1
) a ON a.id_tickets = tickets.id_tickets
GROUP BY tickets.cat_tickets;
SQL Fiddle Demo
Although I am fully clear on what you want, just try this query if the result of this is what you are expecting.
SELECT tickets.cat_tickets, COALESCE(SUM(finance.sold_finance), 0) AS total_sold, COALESCE(SUM(access.scan_access), 0) AS total_scan
FROM finance LEFT JOIN tickets ON finance.id_tickets = tickets.id_tickets
LEFT JOIN access ON access.id_tickets = tickets.id_tickets
WHERE access.id_event = 235
GROUP BY tickets.cat_tickets
ORDER BY tickets.cat_tickets DESC
Disclaimer: This query is not tested due to incomplete data on the question.
SELECT z.Cat_tickets,
COALESCE(x.total_sold,0) total_sold,
COALESCE(y.total_scan,0) total_scan
FROM tickets z
LEFT JOIN
(
SELECT a.id_tickets,
a.cat_tickets,
SUM(b.sold_finance) total_sold
FROM tickets a
INNER JOIN finance b
ON a.id_tickets = b.id_tickets
WHERE id_event = 235
GROUP BY a.id_tickets, a.cat_tickets
) x ON z.id_tickets = x.id_tickets
LEFT JOIN
(
SELECT aa.id_tickets,
aa.cat_tickets,
SUM(bb.scan_access) total_scan
FROM tickets aa
INNER JOIN Access bb
ON aa.id_tickets = bb.id_tickets
WHERE id_event = 235
GROUP BY aa.id_tickets, aa.cat_tickets
) y ON z.id_tickets = y.id_tickets