MYSQL - apply a where clause to only some fields - mysql

I have this table in MYSQL:
Year Type Value ID
0 0 5 1
2010 1 6 1
2011 1 4 1
2012 1 5 1
2013 1 7 1
2014 1 8 1
2015 1 5 1
0 0 6 2
2009 1 7 2
2010 1 4 2
2011 1 2 2
2012 1 8 2
2013 1 8 2
2014 1 5 2
I want to select the minimum and maximum year for each person (IDs 1 and 2), but I also want to select the value associated with type 0 for each person as well. Ideally this is what the query result would look like:
ID MinYear MaxYear Type0Value
1 2010 2015 5
2 2009 2014 6
The query should look, I think, something like this...
select ID,
(min(year) where type = 1) as MinYear,
(max(year) where type = 1) as MaxYear,
(value where type = 0) as Type0Value
from table
group by ID
But this is obviously not correct SQL syntax. How do I do this?

strange table structure, but:
select
_type0.id,
_type0.value,
_type1._min,
_type1._max
from
tbl as _type0
inner join (
select
id,
min(year) as _min,
max(year) as _max
from
tbl
where
1 = type
group by
id
) as _type1 on
_type0.id = _type1.id
where
0 = _type0.type;

you should use inner join.
one half will handle the min and max, second half the type0value:
select a.minYear, a.maxYear, a.id, b.type0value from
(select min(year) as minYear, max(year) as maxYear, id from table where id = 1 group by id) as a
inner join table as b on a.id = b.id
where b.type = 0

Your pseudo-code is actually pretty close. You just need conditional aggregation:
select ID,
min(case when type = 1 then year end) as MinYear,
max(case when type = 1 then year end) as MaxYear,
max(case when type = 0 then value end) as Type0Value
from table
group by ID;
If there could be multiple rows with type = 0, you might want group_concat() instead.

Related

How to Combine multiple rows to single row based on a column in MySQL or Hive

I need to generate average sales per Title between year 2019 to 2021. There are 2 input tables:
Title Table
Title_id Title_type Price_per
1 tv 10
2 book 50
3 cd 20
Transactions table(trans)
tran_id Title_id Qty year
1 3 2 2019
2 1 1 2019
3 3 5 2020
4 3 3 2020
5 1 10 2021
The expected result should generate below columns:
Title_id|Avg_sales_2019|Avg_sales_2020|Avg_sales_2021
title_id avg_sales_2019 avg_sales_2020 avg_sales_2021
1 10.0 NULL 100.0
3 40.0 80.0 NULL
I used below query, but it does not generate the expected output
select a.title_id,
case when a.year=2019 then avg end as Avg_sales_2019,
case when a.year=2020 then avg end as Avg_sales_2020,
case when a.year=2021 then avg end as Avg_sales_2021
from (Select t.title_id, x.year, AVG(t.Price_per*x.Qty) as avg
from title t join trans x on t.title_id=x.title_id
group by t.title_id,x.year) a;
title_id avg_sales_2019 avg_sales_2020 avg_sales_2021
1 10.0 NULL NULL
1 NULL NULL 100.0
3 40.0 NULL NULL
3 NULL 80.0 NULL
How to combine the rows for a particular title_id to get the expected result
Note: I am running the query in Hive
Use conditional aggregation:
SELECT
t.title_id,
AVG(CASE WHEN x.year = 2019
THEN t.Price_per * x.Qty ELSE 0 END) AS avg_sales_2019,
AVG(CASE WHEN x.year = 2020
THEN t.Price_per * x.Qty ELSE 0 END) AS avg_sales_2020,
AVG(CASE WHEN x.year = 2021
THEN t.Price_per * x.Qty ELSE 0 END) AS avg_sales_2021
FROM title t
LEFT JOIN trans x
ON x.title_id = t.title_id
GROUP BY
t.title_id
ORDER BY
t.title_id;

Select difference based on record having minimum and maximum date in MySql

Below is my table let's call account
**ID accountID score tracking_date
1 1 3 2014-09-25 00:01:05
2 2 4 2014-09-26 01:05:18
3 1 6 2014-09-27 09:23:05
4 2 9 2014-09-28 20:01:05
5 1 1 2014-09-28 23:21:34
6 3 7 2014-09-21 00:01:00
7 2 1 2014-09-22 01:45:24
8 2 9 2014-09-27 14:01:43
9 3 1 2014-09-24 22:01:27
I want to select record with max date and also the difference of score with the records having tracking_date as minimum for that accountId. So I want output like below
ID accountID score_with_maxdate diff_score_with_mindate max_tracking_date
1 1 1 -2 2014-09-28 23:21:34
2 2 9 8 2014-09-28 20:01:05
3 3 1 -6 2014-09-24 22:01:27
Any help?
Here is one option. We can self-join a subquery which finds both the min and max tracking dates, for each account, twice to your original table. This will bring in all metadata for those max tracking date records, including the scores.
SELECT
t1.accountID,
t2.score AS score_with_maxdate,
t2.score - t3.score AS diff_score_with_mindate,
t1.max_tracking_date
FROM
(
SELECT
accountID,
MAX(tracking_date) AS max_tracking_date,
MIN(tracking_date) AS min_tracking_date
FROM yourTable
GROUP BY accountID
) t1
INNER JOIN yourTable t2
ON t1.accountId = t2.accountID AND t2.tracking_date = t1.max_tracking_date
INNER JOIN yourTable t3
ON t1.accountId = t3.accountID AND t3.tracking_date = t1.min_tracking_date
ORDER BY
t1.accountID;
Demo
This is a somewhat tricky question. I think conditional aggregation is a convenient way to solve the problem:
select min(t.id) as id, t.accountId,
max(case when t.tracking_date = t2.max_td then t.score end) as score_with_maxdate,
max(case when t.tracking_date = t2.max_td then t.score
when t.tracking_date = t2.min_td then - t.score
end) as diff_score_with_mindate,
max(t.tracking_date) as max_tracking_date
from t join
(select t2.accountId, min(t2.tracking_date) as min_td, max(t2.tracking_date) as max_td
from t t2
group by t2.accountId
) t2
on t.accountId = t2.accountId
group by t.accountId;
Another hackish way of getting same results by using aggregate and string fucntion
select t.accountID,
t.score_with_maxdate,
t.score_with_maxdate - t.score_with_mindate score_with_maxdate,
t.max_tracking_date
from(
select accountID,
substring_index(group_concat(score order by tracking_date desc),',', 1) + 0 score_with_maxdate,
substring_index(group_concat(score order by tracking_date asc),',', 1) + 0 score_with_mindate,
max(tracking_date) max_tracking_date
from demo
group by accountID
) t
Demo
But i would suggest you to go with other solutions mentioned by Tim & Gordon

SQL query: multiple count group by date

I have 2 tables in my mySQL database:
Table Sensor
_id Name
1 Sensor1
2 Sensor2
Table History
_id Sensor_fk Date
1 1 2015-05-24
2 2 2015-05-27
3 1 2015-05-28
4 1 2015-05-28
5 2 2015-05-28
...
I need a query that return something like this:
Date Sensor1 Sensor2
2015-05-24 1 0
2015-05-27 0 1
2015-05-28 2 1
that is the count of my 2 sensors grouped by date. I will populate a bar chart with this data.
Someone can help me?
You need to do a UNION on two individual GROUP BY clauses for each Sensor. Like
(Select count(*) as Sensor1 from History h
where h.Sensor_FK = 1
group by DateField
)
Union
(Select Count(*) as Sensor2 from History h
whre h.Sensor_FK = 2
group by DateField
)
I got it.
SELECT h.date as Date,
count(CASE WHEN h.sensor_fk = 1 THEN h.sensor_fk END) as 'Sensor1',
count(CASE WHEN h.sensor_fk = 2 THEN h.sensor_fk END) as 'Sensor2'
FROM history h
GROUP BY Date

mysql compare 2 rows same table

I am trying to compare 2 rows and display the same ones.I did browse but was not able to find the right solution.
Table A
Count status Division
20 A 1
30 B 2
10 c 1
12 z 1
From the above table I want to display whose division is same.
Count status Division
20 A 1
10 c 1
12 z 1
Try this
Select * from TableA
Group By Division
Having Count(*) > 1
Select * from TableA
Group By Division
having Count(*) = 1
Here i used case statement , it worked for me
select CompanyCode ,'Commission Pec', Year
,sum(case when CommissionType='Commission Recevied' then JAN else 0 end)/sum(case when CommissionType='Net Payments from WM' and isnull(JAN,0)<>0 then JAN else 1 end)
from Commission_Consolidate
group by CompanyCode,Year
end

Display results in a particular format MYSQL

I have a table like
ID Name Points
1 A 10
1 A 11
1 B 11
1 B 12
1 C 12
1 C 13
2 A 8
2 A 9
2 B 9
2 B 10
2 C 10
2 C 11
I want my output to look like the following
ID Average(A) Average(B) Average(C)
1 10.5 11.5 12.5
2 8.5 9.5 10.5
The following group by query displays the output but not in above format
Select Avg(Points),ID,name from table group by Name,ID
Thanks
Wrapping your existing query in a subquery will allow you to build out a pivot table around it. The `MAX()
aggregate's purpose is only to eliminate the NULLs produced by the CASE statement, and therefore collapse multiple rows per ID down to one row per ID with a non-NULL in each column.
SELECT
ID,
MAX(CASE WHEN Name = 'A' THEN Points ELSE NULL END) AS `Average (A)`,
MAX(CASE WHEN Name = 'B' THEN Points ELSE NULL END) AS `Average (B)`,
MAX(CASE WHEN Name = 'C' THEN Points ELSE NULL END) AS `Average (C)`
FROM (
SELECT ID, AVG(Points) AS Points, Name FROM yourtable GROUP BY Name, ID
) avg_subq
GROUP BY ID
Here is a live demonstration on SQLFiddle