For starters, I'm a super novice in SQL, and so I don't have the knowledge to ask a straightforward question, but I'll do my best. Here is the query I'm trying to make:
query = conn1.prepareStatement(
"select Industry, Ticker, TransDate, min(TransDate), max(TransDate), " +
" count(distinct TransDate) as TradingDays, " +
" count(distinct Ticker) as TickerCnt, " +
" openPrice, closePrice " +
" from Company left outer join PriceVolume using(Ticker) " +
" group by Industry " +
" having TradingDays >= 150 " +
" order by Industry, Ticker, TransDate");
ResultSet rs = query.executeQuery();
Here's the Error:
SQLException: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'reedy330.Company.Ticker' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
If I include Ticker and TransDate in the GROUP BY clause, the exception no longer happens, but the ResultSet is empty. What I'm trying to do is have a ResultSet with everything in the SELECT clause as elements. I built this query from a similar example query in the assignment description, which is why I don't understand it well.
Here is the layout of the database, table names bolded with a colon, keys are just in bold:
PriceVolume:
Ticker
TransDate
OpenPrice
HighPrice
LowPrice
ClosePrice
Volume
AdjustedGross
Company:
Ticker
Name
Industry
Location
Any ideas?
Is "sql_mode=only_full_group_by" necessary for you?
If not, change the sql_mode:
SET sql_mode = '';
OR
SET sql_mode = 'STRICT_ALL_TABLES';
When you're using group by, everything in your select clause must EITHER be an aggregate function (like min, max, count etc), OR be in the group by clause.
You need to include Ticker and TransDate in the group by clause.
Related
I am trying to insert into a table the results which I just selected from this query, But I can't figure it out.
List<Object[]> results = em.createQuery("SELECT s.competition_id, s.data, s.discipline, s.category, s.player_id,"
+ " s.playerFirstName, s.playerLastName, SUM(s.points) as points FROM Score s"
+ " GROUP BY s.competition_id, s.player_id "
+ " ORDER BY s.points DESC", Object[].class).getResultList();
This select is working, but I need to insert this into the result table.
You can use Insert Select statement into regular SQL. You just need to provide the same amount of compatible columns into the query. I think it should be possible with group by records as well.
You may use Insert Selects with my Daobab (http://www.daobab.io)
An example:
https://github.com/daobab-projects/daobab-100plus-examples/blob/main/src/main/java/io/daobab/demo/example/c_talented/InsertSelect.java
I am working on converting a legacy MS access system to a spring-boot application and I came across a big query. I am mostly done with converting the functions from access to mysql but not able to understand how to convert the following DLookUp sub-query as a mySql subquery
DLookUp("[price]","tbl_so","[so_id] = " & tbl_trade.so_id & " AND [product_id] = " & tbl_po.product_id
What I understood is following won't work as I don't have the Inner Joins set between the 3 tables, tbl_so, tbl_po, tbl_trade
SELECT tbl_so.price FROM tbl_so WHERE tbl_so.so_id = tbl_trade.so_id AND tbl_so.product_id = tbl_po.product_id
My question is how do I know how the tables will join with each other in this case and also when this DLookUp query is seldom used. And also the solution for this query.
Well, as a general rule, dlookup() can be replaced with a left join. However, you can also use a sub-query and they tend to be "less" change to the query.
So, if we had this:
SELECT id, partNum, dlookup("PartDescrt","tblParts","PartID = " & partNum)
as Description from tblOrders.
You would replace the above dlookup() with a sub-query like this:
SELECT id, partNum,
(select PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum)
AS Description
from tblOrders
The above is SQL or access sql syntax, but quite sure the same should work for MySQL.
If there is more then one partNumber that matches the above, then add a TOP 1, and a order by with some unique row (PK ID column is best). So the query becomes:
(select TOP 1 PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum
ORDER BY PartDescrt, ID DESC)
AS Description
I´m starting with Hibernate.
I have 2 tables in MySQL DB.
1)Unit
2)type: has as foreign key Unit_IdUnit
I have also in type a column name "Period" VARCHAR
I want to create this query on HQL:
SELECT *
FROM unit
WHERE IdUnit not in(SELECT Unit_IdUnit
FROM type
WHERE Period='2016-09');
If I run this query in Mysql it´s working. But I can´t make it works on HQL.
How could I create this query to return a list of Unit?
This is my first question, so please let me know if you need further information
You can use below HQL:
session.createQuery(
"from unit where IdUnit not in (SELECT Unit_IdUnit
FROM type
WHERE Period='2016-09')"
).list();
This is how I fix it.
Query query= session.createQuery("SELECT e1 FROM Unit e1 "
+ "WHERE e1.idUnit NOT IN ("
+ "SELECT e2.unit "
+ "FROM type e2 "
+ "WHERE e2.period=:period)");
query.setParameter("period", "2016-09");
list= query.list();
Here's my code
SELECT res.type,
res.contactname,
res.id,
res.inv_addressline2,
res.inv_addressline3,
res.signup_date,
res.engineer_id_global,
res.job_id_global,
res.neg_or_pos,
res.rating,
res.author_id_global,
res.timestamp_global,
res.short_description,
res.job_title,
res.feedback,
author_data.contactname AS `author_name`,
review_count.total_feedback,
review_count.total_rating
FROM (SELECT mb.type,
mb.contactname,
mb.id,
mb.inv_addressline2,
mb.inv_addressline3,
mb.signup_date,
fb.engineer_id AS `engineer_id_global`,
fb.timestamp AS `timestamp_global`,
fb.job_id AS `job_id_global`,
fb.neg_or_pos,
fb.rating,
fb.feedback,
fb.author_id AS `author_id_global`,
ac.engineer_id,
ac.timestamp,
ac.author_id,
jb.job_id,
SUBSTR(jb.job_description, 1, 200) AS `short_description`,
jb.job_title
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . ACCEPTED . " AS ac
ON mb.id = ac.engineer_id
LEFT JOIN " . FEEDBACK . " AS fb
ON ac.job_id = fb.job_id
LEFT JOIN " . JOBS . " AS jb
ON fb.job_id = jb.job_id
WHERE mb.type = 2
ORDER BY
fb.timestamp DESC
) AS res
LEFT JOIN
(SELECT mb.id,
mb.contactname,
fb.author_id
FROM " . MEMBERS_TABLE . " AS mb
LEFT JOIN " . FEEDBACK . " AS fb
ON fb.author_id = mb.id
LIMIT 1
) AS `author_data`
ON res.author_id_global = author_data.author_id
LEFT JOIN
(SELECT COUNT(fb.engineer_id) AS `total_feedback`,
SUM(fb.rating) AS `total_rating`,
fb.engineer_id
FROM " . FEEDBACK . " AS fb
) AS `review_count`
ON res.engineer_id_global = review_count.engineer_id
GROUP BY res.contactname
ORDER BY res.contactname
I'm just starting to get my head around SQL. My worry is the second and third inner query. Am I right in saying it will return all results as there is no where clause and the return the results from that using the "ON" statement or is the "ON" statement combined with the initial query?
There are a number of issues with this script:
You have a number of tables with names like " . MEMBERS_TABLE . ", " . ACCEPTED . " and so on. These are unlikely to be acceptable in MySQL, which normally uses backticks (`) to quote object names; if this script is to be preprocessed by eg. Perl or Python, or is part of a larger script in another language, it would be helpful to say so.
You have an order by clause, for no apparent reason, in your first sub-query. This could be removed.
Your second sub-query links FEEDBACK to MEMBERS_TABLE and limits the results to 1, without specifying the author_id inside the sub-query - this means that a single, random member will be selected inside the sub-query, then linked to the rest of the dataset on the specific author ID, which won't match for most of the rest of the dataset.
The FEEDBACK table is completely irrelevant here, and can be removed.
If id uniquely identifies a record on MEMBERS_TABLE, the sub-query can be completely removed and replaced with a single left join to MEMBERS_TABLE on res.author_id_global = MEMBERS_TABLE.id. No limit clause would be required.
If id does not uniquely identify a record on MEMBERS_TABLE, the sub-query should be rewritten as select distinct id, contact_name FROM " . MEMBERS_TABLE . " AS mb where res.author_id_global = mb.id LIMIT 1. If there are multiple matching authors for the same id, one would be selected at random.
The third sub-query does not require a where clause - it will summarise all engineers' feedback and ratings by engineer within the sub-query, and each engineer will then be linked to the corresponding engineer from the rest of the dataset by the on condition from the left join clause.
Second inner query is having limit 1. It is nothing but where condition to show only one result. Third inner query is not having any problem.
Problem:
I originally had a query that was working great but I'm now having to change it to pull more fields. When I try run the new query it picks a field name and says that I haven't included it as part of the aggregate function. Each time I get this error I can add the field the error specifies to the Group By statement and the error message will choose a new field that isn't included. Anyone have any idea's as to how I can get the same information I was getting with the original query just with more fields?
Description of how query is supposed to work:
The query is meant to pull one record for each distinct set of readings_miu_ids and ReadDates (The PremID field is the same for each distinct readings_miu_id).
Original Query:
strSql3 = " SELECT Distinct readings_miu_id, ReadDate, PremID " & _
"INTO analyzedCopy2 " & _
"FROM analyzedCopy "
DoCmd.SetWarnings False
DoCmd.RunSQL strSql3
DoCmd.SetWarnings True
New Query:
strSql3 = " SELECT Top 1 readings_miu_id, Reading, ReadDate,Format([MIUtime],'hh:mm:ss') AS ReadTime,MIUwindow,SN,Noise,RSSI,ColRSSI,MIURSSI,Firmware,CFGDate,FreqCorr,Active,MeterType,OriginCol,ColID,Ownage,SiteID,PremID , Neptune_prem.prem_group1, Neptune_prem.prem_group2,ReadID " & _
"INTO analyzedCopy2 " & _
"FROM analyzedCopy " & _
"Group By readings_miu_id, ReadDate, PremID " & _
"Order By readings_miu_id, ReadDate, ReadID, PremID "
DoCmd.SetWarnings False
DoCmd.RunSQL strSql3
DoCmd.SetWarnings True
In my experience (which is only moderate) every column in the result set (but NOT every aggregate) must be in the group by.
Here's a decent reference
When you include a GROUP BY clause, each field must either be in the GROUP BY or have an aggregate function (e.g, MAX, MIN, SUM, COUNT) applied to it.
For example, a simple correct implementation might be:
SELECT Department, MAX( Salary ) FROM Employees GROUP BY Department
... and a simple incorrect implementation would be:
SELECT Department, Salary FROM Employees GROUP BY Department.
Consider the two statements above. For the first, you can easily imagine what a datasource would look like and what would be returned. However for the second, what would you return? Which individual value of Salary would you return in your resultset? Hence, when you group fields, each field in the result set must either participate in the GROUPing or be the result of an aggregation of the values collected from the group comprised of the other fields.
You can accomplish this via a subquery or two queries. Also, "CurrentDb.Execute" is the preferred method to run a query like this (instead of "DoCmd.RunSQL").
CurrentDb.Execute strSQL3, dbFailOnError