Creating a view off another view - mysql

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

Related

single (unique) results in sql query result

I'm really stuck:
A little background: I've build a website with a database with multiple tables.
It is about minerals that have fluorescense under different types of UV light (long wave, medium wave and short wave, LW, MW and SW)
The website is working fine, however, with a little bit too much results.
I have a table with all the details of the minierals, I have a table where I put the photo's and with those photo's I save what kind of UV is used.
Now I want a query that filters for specific wave lengts; but I get double results since I've multiple photo's with a specific wave length, see yellow marking in example. 19 results instead of 18 results
How do I get the distinct results? So, in this case, how do I get 18 unique results instead of 19 results as shown?
The query I use right now is
SELECT m.korte_naam, m.url_naam, m.mineraal_id, m.opmerking, m.vindplaats_kort, m.gewicht from `mineraal` m, `foto` f where m.mineraal_id = f.mineraal_id and f.lichtbron = 'SW';
Any help is highly appreciated!
If you only want to select each item once, you can use:
SELECT DISTINCT m.korte_naam, m.url_naam, m.mineraal_id, m.opmerking, m.vindplaats_kort, m.gewicht from `mineraal` m, `foto` f where m.mineraal_id = f.mineraal_id and f.lichtbron = 'SW';
If you want not to keep the same record more than once, you need to check before insertion that record hadn't been inserted already.

How do I select rows that contain any of the selected values in any of the selected columns? MySQL

I'm pretty much trying to get all of the rows that contain any of the relevant tags in any of the relevant columns.
Take a look at an example row:
[LeadID Leadname Ratings AvgRating Address Website Phone TimesOpen Category LeadDescription CurrentStatus]
1 Siena Tuscan Steakhouse 396 4.300 104 S Broadway, Wichita, KS 67202, United States http://www.sienawichita.com/ +1 316-440-5300 LGBTQ+ friendly2022-05-19 Thursday 5PM–12AM
2022-05-20 Friday 6:30–10AM
2022-05-21 Saturday 7–11AM
2022-05-22 Sunday 7–11AM
2022-05-23 Monday 6:30–10AM
2022-05-24 Tuesday 6:30–10AM
2022-05-25 Wednesday 5PM–10AM
restaurants Hotel restaurant-bar offering refined Italian plates & many wines in a warm & elegant atmosphere.
I don't think you'll need to see it in structured form so I apologize for it being messy.
Everything in [ ] are the column names, and the following are its respective fields.
Here is my query
SELECT LeadID
FROM cleancopy
WHERE
Website OR LeadName OR LeadDescription OR Category
IN ('%Event%' OR '%Live%' OR '%Music%' OR '%Venue%');
This query is returning all rows unfiltered.
I want the query to select all rows that contain any number of the relevant tags "Event", "Live", "Music", "Venue", in any of the column names Website, LeadName, LeadDescription, Category.
So one or all of the tags could be in one or all of the attribute types.
More simply put, I'm trying to filter out any row that doesn't contain any of the keywords I want.
First thing: "I don't think you'll need to see it in structured form" is a very bad assumption. We DO need this because it makes it much easier to provide a good answer.
Second thing: This is not the kind of data checking SQL is done for. So there is no simple way especially when you really need a list of strings and a like condition. Such complex data handling should better be avoided or done outside SQL and within the application.
Anyway, the shortest way to do what you describe will be to CONCAT all columns and then search for your strings using OR.
SELECT leadid FROM cleancopy WHERE
CONCAT(website,leadname,leaddescription,category) LIKE '%Event%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Live%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Music%'
OR CONCAT(website,leadname,leaddescription,category) LIKE '%Venue%'

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).

SQL SUM condition on each column

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

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.