I need to sum the data from two different columns located in different tables and grouped by session_id.....
I need to sum the column of spent_points + price_points grouped by session_id
this is the result i hope to get
I have tried with this query but I have only managed to group the data but I have not been able to sum it by session_id
SELECT session_details.session_id,SUM(session_details.spent_points) AS total_sum_session FROM session_details WHERE session_details.session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy") GROUP BY session_details.session_id UNION SELECT template_sales.session_id, SUM(template_sales.price_points) AS total_sum_sales FROM template_sales WHERE template_sales.session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy") GROUP BY template_sales.session_id
First use UNION ALL to get all the rows from the 2 tables that you want and then aggregate:
SELECT session_id, SUM(points) AS total_points
FROM (
SELECT session_id, spent_points AS points
FROM session_details
WHERE session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
UNION ALL
SELECT session_id, price_points
FROM template_sales
WHERE session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
) t
GROUP BY session_id
You're almost there:
WITH union_rows (session_id, points) AS (
SELECT session_details.session_id, session_details.spent_points
FROM session_details
WHERE session_details.session_id IN ('-Meagevy6y9ukbmFXvB7','-Meak6dG9iqvHWfAGQvy')
UNION ALL
SELECT template_sales.session_id, template_sales.price_points
FROM template_sales
WHERE template_sales.session_id IN ('-Meagevy6y9ukbmFXvB7','-Meak6dG9iqvHWfAGQvy')
)
SELECT session_id
, SUM(points) AS total_sum
FROM union_rows
GROUP BY session_id
;
If you have an older version of MySQL, without WITH clause support, use a derived table instead.
The session_id filter can be done outside the CTE term, but then you may carry all those other rows as well, until the filter is processed.
Maybe you can do a JOIN between this two tables using the session_id.
After that you can sum the two attributes.
It'll be something like this:
SELECT session_details.session_id,SUM(SD.SPENT_POINTS + TSS.PRICE_POINTS ) AS total_sum_session
FROM session_details SD
JOIN template_sales.session_id TSS ON SD.SESSION_ID = TSS.SESSION_ID
WHERE SD.session_id IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
GROUP BY SD.session_id
Try this:
SELECT A.session_id,SUM(A.Total) AS Total
FROM
(
SELECT session_details.session_id,session_details.spent_points AS Total
FROM session_details
WHERE session_details.session_id IN ("-Meagevy6y9ukbmFXvB7","-
Meak6dG9iqvHWfAGQvy")
UNION ALL
SELECT template_sales.session_id, template_sales.price_points AS Total
FROM template_sales
WHERE template_sales.session_id
IN ("-Meagevy6y9ukbmFXvB7","-Meak6dG9iqvHWfAGQvy")
) AS A
GROUP BY A.session_id
Related
I’m trying to retrieve the number of unique users that have made a purchase in a monthly basis. This sounds simple but the problem here is that we have three type of products and the purchases of these products are on different tables in which the only common key is the user_id, so in order to find out unique users I have to query the three tables separately, union the results and execute a count distinct.
Here’s an example of what I’m doing right now:
SELECT
month,
count(distinct user_id) as users
FROM
(
SELECT
DATE_FORMAT(purchase_date,’%Y-%m) as month,
user_id
FROM purchases_a
UNION
SELECT
DATE_FORMAT(purchase_date,’%Y-%m) as month,
user_id
FROM purchases_b
UNION
SELECT
DATE_FORMAT(purchase_date,’%Y-%m) as month,
user_id
FROM purchases_c
)
GROUP BY 1
Is this the only way to go? This query takes forever. Thanks!
One method is to use union all in a subquery and then aggregate:
select DATE_FORMAT(purchase_date, '%Y-%m') as month,
count(distinct user_id)
from ((select user_id, purchase_date from purchases_a) union all
(select user_id, purchase_date from purchases_b) union all
(select user_id, purchase_date from purchases_c)
) p
group by month
I have this table
i want to ignore productNo and sum all product count accordingly.
select sum(count), max(productNo)
from Table
where date between 117 and 118
group by product
this one gives wrong result...
I want to have sum of counts for each Product-ProductNo combination
try like below
select product,productno,sum(count) as result
from table_name
where productno='X1'
group by product,productno
seems you need the firts rows order by result
select product,productno,sum(count) as result
from table
group by product,productno
order by result
limit 1
Since you haven't tagged any DBMS so, i would use row_number():
select t.*
from (select product, productno, sum(count) as cnt,
row_number() over (partition by product order by sum(count) desc) as seq
from table t
group by product, productno
) t
where seq = 1;
You can also use LIMIT clause (but not for each product) :
select product, productno, sum(count) as cnt
from table t
group by product, productno
order by cnt desc
limit 1;
Some other DBMS requires TOP clause instead of LIMIT clause so, you can change accordingly but the idea would be same.
select sum(count), max(productNo)
from Table
where date between 117 and 118
group by product, productNo
with this it works :)
I'm a beginner at SQL, how do I get a query which returns the most prevalent column value? Probably there is an answer somewhere but I don't know how to google it.
For example in the user_id column the query should return the value 1 because this is the most prevalent number.
One approach is to do a GROUP BY aggregation and then apply a LIMIT trick:
SELECT user_id, COUNT(*) AS cnt
FROM yourTable
GROUP BY user_id
ORDER BY COUNT(*) DESC
LIMIT 1;
If you want something more complex, then you would be getting into the realm of rank functionality. MySQL (at least as of the current release) does not support built-in rank support, so it can be tricky to perform such queries.
SELECT top 1 user_id, COUNT(*) AS cnt
FROM yourTable
GROUP BY user_id
ORDER BY COUNT(*) DESC
Have a common table expression that counts each user_id. Select user_id where the count is the max count. Will return both user_id's in case of a tie.
with cte as
(
SELECT user_id, COUNT(*) AS cnt
FROM yourTable
GROUP BY user_id
)
select user_id
from cte
where cnt = (select max(cnt) from cte)
I have come across a task, I managed to complete the objective but the solution I got is not optimum, I need more optimum solution. I have used normal Sub Queries May be Correlated Sub Query can solve this better.
This is the table i made
SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid;
The output of this is like:-
What I want is the custid having maximum Total.
One way to do it is using Order by Total DESC LIMIT 1 but this will give only 1 result.
What I did is
SELECT custid
FROM (SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid) c1
WHERE total = (SELECT max(Total)
FROM (SELECT custid,
count(DISTINCT bid) AS Total
FROM loan
GROUP BY custid) c2)
This gives me correct result that is
What I want to do is reduce the code, because here I am writing the same thing again. I know there must be a simpler way to do it. Maybe a correlated query.
Looking for some good answers. This is basically to clear my concepts only
Sorry, if it is noob question. I am a noob to SQL.
After understand what OP want with #Ravinder 's tip,
I guess build in mysql function GROUP_CONCAT is what you need, sql is:
select custid_count.Total, GROUP_CONCAT(custid_count.custid order by custid_count.custid asc SEPARATOR ',') as custids from
(select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
group by custid_count.Total
order by custid_count.Total desc
limit 1;
the result column custids is the max ids concated by ',' ,after the query, you need to split custids by ',' and convert each substring to number type you need,
Here is another way:
select * from loan
where custid =
(
select custid_count.custid from
(select custid, count(distinct bid) as Total from loan group by custid order by Total desc) as custid_count
order by custid_count.Total desc
limit 1
);
First find the custid with max count, then query all rows which match the custid,
I haven't tried this in mysql, but in the sql language I'm using it is fine to use a aggregation function without a group by so something like this
select custid, total, max(total) as maxtotal
from (select custid, count(distinct bid) as total
from loan
group by custid) c1;
would tag on every line both the individual customer total and the table wide max total, and you'd just have to filter on the ones that where the total was equal to the max total. That would give you a final answer of something like this:
select custid
from (select custid, count(distinct bid) as total
from loan
group by custid) c1
where total = max(total);
Is there any other way to write this query ?
I tried doing it in a subquery but it doesn't work because of the multiple columns. It seems like this query only works by itself. Please correct me
Records
PK recordId
dateViewed
CarViewed
I tried this
SELECT R.`dateViewed` FROM Records ,(
SELECT R.CarViewed, COUNT(R.CarViewed) as cnt FROM Records R
GROUP BY R.CarViewed
ORDER BY cnt DESC
LIMIT 1 ) AS favouriteCarOfTheDay
GROUP BY R.`dateViewed
Then I tried this
SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt FROM Records ,
(
SELECT R.CarViewed FROM Records R
GROUP BY R.CarViewed
ORDER BY cnt DESC
LIMIT 1 ) AS favouriteCarOfTheDay
GROUP BY R.`dateViewed
Along many other queries I tried, I have no idea how to get it working.
In a nutshell for a specific date, I would like to get the most common cars that were viewed.
Like :
dateViewed favouriteCarOfTheDay
2012-09-22 | Nissan
2012-09-23 | BMW
try this
SELECT R.`dateViewed` ,COUNT(R.CarViewed) as cnt ,R.CarViewed FROM Records R
GROUP BY R.`dateViewed
ORDER BY COUNT(R.CarViewed) DESC
I think the following should work (disclaimer, not all my own work, adapted from an answer at another question)
SELECT DISTINCT
R.dateViewed,
R.CarViewed
FROM Records R
WHERE
R.dateViewed =
(SELECT R2.dateViewed FROM
(
SELECT R1.dateViewed, COUNT(*) AS numViewed
FROM Records R1
WHERE R1.CarViewed = R.CarViewed
GROUP BY R1.dateViewed
ORDER BY R1.numViewed DESC
) AS R2
LIMIT 1
)
ORDER BY r.dateViewed
Such things are really awful to do in MySQL so it might actually by slower than two correlated subquery but at least it returns both the car and it's viewcount:
SELECT counts.`dateViewed`,counts.`CarViewed` as favourite_car, counts.cnt
FROM
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt
FROM Records
GROUP BY R.`dateViewed` ,R.`CarViewed`
) as counts JOIN
(SELECT R.`dateViewed`, MAX(cnt) as cnt
FROM
(SELECT R.`dateViewed` ,R.`CarViewed`, COUNT(*) as cnt
FROM Records
GROUP BY R.`dateViewed` ,R.`CarViewed`
) as q
GROUP BY R.`dateViewed`) as maxes
ON counts.cnt=maxes.cnt