SQL SUM condition on each column - mysql

I'm giving my best efforts to write a query to get the desired output format shown the second table here. Is there a better way to achieve this, table 1 has the raw data and I want to find the sum of monthly usage of unique devices for a given user. Any help is really appreciated.
table format
Apologize for not being clear in first place. tagged different image to illustrate better. If you look at this data in new image attached. After I filter by username - I get that data output. My need is to get the sum of usage by month by device.
Ex: rows highlighted in the image, where iPhone-6sPlus is used multiple times each month across months. I'm looking for a query that gives output as
iPhone-6SPlus is used xx_hrs in Jan, yy_hrs in feb so on. Similarly for other device models. Hope this helps. Thanks.
Better image

create table #product (model varchar(50),users varchar(5), monthofuse Varchar(3),yearofuse int,usage int)
Insert into #product values('X','a', 'JAN',2010,34), ('X','a', 'Feb',2010,20),('X','a', 'Mar',2010,10),('Y','a', 'Jan',2010,30),
('Y','b', 'Jan',2010,30),('Y','b', 'Feb',2010,30),('X','a', 'JAN',2011,50)
select * from #product
Select * FROM
(Select users,monthofuse,usage,model from #product) q
Pivot
(
sum(usage) for q.monthofuse in([JAN],[FEB],[MAR],[APR],[MAY],[JUN],[JUL],[AUG],[SEP],[OCT],[NOV],[DEC]))As pvttable

Related

SQL - How to select/delete rows with the max value depending on two others

I'm an intern in a property rental company. I'm in charge of developping the CRM under Symfony.
So, ones of my entities are properties (houses) and their availabilities. See the table structure below.
The problem I'm facing for now, is that the availabilities had been defined for each day (e.g. 28/01, 29/01, 30/01) instead of being defined for a range of day (e.g. 28/01 -> 30/01). So, the table is really heavy (~710 000 rows). Furthermore, before we changed the way of editing an availability, it created a new row for a same date instead of editing it. So, there are a lot of duplications in this table.
What I want, is to lighten the DB by keeping only the rows which have the max value in date_modif_availabilities for the same date_availabilities and id_properties.
For example, if I have these rows (availabilities_duplications):
I only want to keep the row with the latest modif like this (availabilities_keep_max_value) :
The thing is, I don't know enough the SQL language. I'm able to write few basics scripts but not complex subqueries. Even with code samples that I found.
Thank you in advance for your help.
You could select the elements for which no element with greater modified date exists.
Something like this:
SELECT avl1.*
FROM availabilities avl1
WHERE NOT EXISTS (SELECT *
FROM availabilities avl2
WHERE avl1.date_availabilities = avl2.date_availabilities
AND avl1.id_properties = avl2.id_properties
AND avl2.date_modif_availabilities > avl1.date_modif_availabilities);
This of course has the pre-condition that the combination of the three columns date_availabilities, id_properties and date_modif_availabilities is unique.
Furthermore, it seems that all columns (except the PK) may be NULL. Looks kinda odd to me.
You can use subquery :
select t.*
from table t
where id_availabilities = (select t1.id_availabilities
from table t1
where t1.id_properties = t.id_properties and
t1.date_availabilities = t.date_availabilities
order by t1.date_modif_availabilities desc
limit 1
);
However, if you have concern about the performance, then you want index on (id_properties, date_availabilities and id_availabilities).

Creating a view off another view

I currently have a view called v_testhorses which pulls data from Horses and Results. It has the following values -
HID|HName|YOB|Gender|Sire|Dam|OName|Stable|LTE|Year
Where LTE = the sum of the earnings field from Results and Year = an individual column created for each year
(for example, if Horse B showed in 2012 and 2011, there'd be only columns for those two years with separate LTEs for each year)
I'm trying to create a view just using the Sire field, while taking these others things into consideration. Ideally it'd look like this -
HID|HName|ProgenyEarnings|Year
Where HName in this case is based off Sire and ProgenyEarnings is the sum of LTE of all horses with that Sire. It'd be a way to look at all horses in v_testhorses and "assign" them to a sire, who is also in the v_testhorses database. It'd be the easiest way to decide who was the highest grossing sire in each year based off their progeny.
I hope this makes sense!
I've been trying the WHERE HName=Sire as a clause and it just gives me an empty view.
You have to join the view with itself to relate the progeny to its sire:
SELECT h1.HID, h1.HName, SUM(h2.LTE) AS ProgenyEarnings, h1.Year
FROM v_testhorses AS h1
JOIN v_testhorses AS h2 ON h1.HName = h2.Sire
GROUP BY h1.HID

Tell from Which table MySQL COALESCE returned the value

i have the following part of query:
SUM(COALESCE(user_a, user_b)) AS income_adsense
Now, i have a html table in my web app where i present the data from this query.
problem is i want to mark data in one color if answer is from col user_a and different color if answer is from user_b col.
is there a way to achieve that in my query itself? (some sort of flag maybe?)
.
right now the only solution i have is to return all col's and work with the data on the client side but i am wondering if there's a cleaner/best practice solution.
guess it's worth mentioning i don't want to change the table structure.
Well, to make sense of the data I would do something like:
CASE
WHEN SUM(user_a) > SUM(user_b)
THEN 'User_A'
ELSE 'User_B'
END [Most of the data comes from]
You could also have two separate SUM() columns to make sense of this and compare the sum of values in your application.
SUM(user_a) [User_A Score Weight]
, SUM(user_b) [User_B Score Weight]

Mysql select part of field and return full value

Good day all,
I have a field called mCodes which has the exact length (7) throughout the table but with different values i.e. a few records with 5036100, 5036102, 5036103, 7010100, 7010101 etc.
I am using a select statement to first search for the first 4 characters i.e 5036 which will return all the records with 5036 just fine
I now need to return the actual full value of the records 5036100 etc. without recreating another sql statement. My statement I am using is as follow -
SELECT LEFT(MCODE, 4), MAKE, MODEL, NEWPRICE23 FROM mautogd1015 WHERE LEFT(MCODE, 4) = '5036'
I have racked my brain over this for a few hours now, any help will be appreciated.
Try something like this.
SELECT MCODE, MAKE, MODEL, NEWPRICE23 FROM mautogd1015 WHERE LEFT(MCODE, 4) = '5036'

How should I write a Query with "Group By Clause" to get following specified output?

I have written a Query in MSBI Query Editor as follows,
SELECT
DATEPART(year,tblReservation.Date) AS "Year",
tblReservation.Room AS "Room No.",
COUNT(tblReservation.Room) AS "No. Of Times",
CASE
WHEN PaidFor = 1
THEN
COUNT(tblReservation.Room)*tblPrice.Price
ELSE 0
END AS "ActualRevenue",
COUNT(tblReservation.Room)*tblPrice.Price AS "TargetRevenue"
FROM tblReservation INNER JOIN tblRoom
ON tblReservation.Room = tblRoom.RoomNumber
INNER JOIN
tblPrice ON tblRoom.PriceID = tblPrice.PriceID
GROUP BY tblReservation.Room, tblPrice.Price,
tblReservation.PaidFor, DATEPART(year,tblReservation.Date)
This Query is showing me output like this(Matrix Layout MSBI),
My Query output is as,
My Report design layout is,
What I want is, in my Matrix layout, the room no. 100 is two times, for year 1999 & 2013.
It is occupying two rows. I want this in one row in my Matrix layout.
How should I do ?
Thanks.
It's difficult to tell what's going on with your matrix without more details, but this should all work fine without any special effort.
Take a subset of your data:
Create a standard matrix, adding a few extra columns to to the column group:
You can see the row group is based off RoomNo and the column group is based off Year. The data cells are just aggregated values. This works as expected for room 100:
Without more detail it's impossible to tell what's causing your issue, but the above shows this is certainly possible with everything as standard.
In your case I would try:
Checking the row groups details and see if it is grouped on anything other than RoomNo; same for the column group and Year.
Create a new text matrix from scratch with the above grouping and see if this new item is working as expected.