MySQL: From SELECT statements to INSERT statement - mysql

I have the following code that returns me two nice tables (When using the SQL function in PhpMyAdmin). However, I am unable to insert them into my TABLE B.
How can I insert this in TABLE B rather than only showing it?
SELECT DateTimeCode, Rat,
MAX(IntendedStimulusDuration_ms) AS StimulusDuration,
SUM(Correct + Incorrect + Omission + PrematureNosepokes) AS total_trials,
SUM(Correct) AS correct,
SUM(Incorrect) AS incorrect,
SUM(Omission) AS omission,
SUM(PrematureNosepokes) AS premature,
SUM(PerseverativePanelPushes) AS P_PanelPushes,
SUM(PerseverativeNosepokes) AS P_nosepokes,
SUM(PerseverativeNosepokesSameHole) AS P_NPsame,
SUM(PerseverativeNOsepokesOtherHoles) AS P_NPother
FROM `FiveChoice_TrialData`
GROUP BY Rat,DateTimeCode;
--If correct = 1
SELECT DateTimeCode, Rat,
AVG(ResponseLatency_ms) AS ResponseLatency,
AVG(CollectionLatency_ms) AS CollectionLatency
FROM `FiveChoice_TrialData`
WHERE Correct = 1
GROUP BY Rat,DateTimeCode;
Basically I tried:
INSERT INTO TABLE_B (--all my col names, just like the alias stated above)
VALUE (--My two select statement as written above, separated by a coma)

You don't need the value statement when inserting from a query. Try this:
insert into table_b(<list of columns here>)
SELECT DateTimeCode, Rat,
MAX(IntendedStimulusDuration_ms) AS StimulusDuration,
SUM(Correct + Incorrect + Omission + PrematureNosepokes) AS total_trials,
SUM(Correct) AS correct,
SUM(Incorrect) AS incorrect,
SUM(Omission) AS omission,
SUM(PrematureNosepokes) AS premature,
SUM(PerseverativePanelPushes) AS P_PanelPushes,
SUM(PerseverativeNosepokes) AS P_nosepokes,
SUM(PerseverativeNosepokesSameHole) AS P_NPsame,
SUM(PerseverativeNOsepokesOtherHoles) AS P_NPother
FROM `FiveChoice_TrialData`
GROUP BY Rat,DateTimeCode;
And something similar for the second query.

Related

Select sum of multiple columns based on the conditions

I want to find addition of low_cvt,med_cvt and high_cvt based on the unique idCampaign. for example in the screenshot, idcampaign 3870576 is repeating twice and it's addition is 12.
Screenshot: https://imgur.com/a/xES9yp2
I am using following statement in select statement:
CVT.low_cvt + CVT.med_cvt + CVT.high_cvt + CVT.other_cvt AS 'All CVT',
however, it is giving duplicate idcampaign.
Thanks,
Sameer
try a query like this:
SELECT CVT.idcampaign,
SUM(CVT.low_cvt+CVT.med_cvt+CVT.high_cvt+CVT.other_cvt) AS 'All CVT'
FROM Your_Table AS CVT
WHERE CVT.idcampaign = 3870576
GROUP BY CVT.idcampaign;

Hibernate Insert Selected

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

DLookUp query to MySql

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

JOIN on keys that don't have the same value

I am trying to do an INNER JOIN on two tables that have similar values, but not quite the same. One table has a fully qualified host name for its primary key, and the other the hosts short name, as well as the subdomain. It it safe to assume that the short name and the subdomain together are unique.
So I've tried:
SELECT table1.nisinfo.* FROM table1.nisinfo INNER JOIN table2.hosts ON (table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com') = table2.hosts.fqhn WHERE table2.hosts.package = 'somepkg';
This doesn't return the results I expect, it returns the first result hundreds of times. I'd like to return distinct rows. It takes a long time to run as well.
What am I doing wrong? I was thinking of running a subquery to get the hostnames, but I don't know what the right path from here is.
Thank you!
You can use group by in your query so you can achieve the desired results you want
please see this two links
Group by with 2 distinct columns in SQL Server
http://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tables
Try putting your results into a temp table and then view the table to make sure that the columns are as expected.
SELECT table1.nisinfo.*, table1.nisinfo.shortname + '.' + table1.nisinfo.subdomainname + '.domain.com' AS ColID
INTO #temp
FROM table1.nisinfo;
Select *
from #temp INNER JOIN table2.hosts ON ##temp.ColID = table2.hosts.fqhn
WHERE table2.hosts.package = 'somepkg'
;
Put a Group By clause at the end of the second statement
So in this case, I used a subquery to get the initial results, and then used a join.
SELECT table1.nisinfo.* FROM table1.nisinfo JOIN (SELECT distinct(fqhn) FROM table2.hosts WHERE package = 'bash') AS FQ ON ((SUBSTRING_INDEX(FQ.fqhn, '.', 1)) = table1.nisinfo.shortname);

Error Converting MySQL Query to SQL Server

Trying to convert below query into SQL, query works fine on MySQL. Problem seems to be the GROUP BY area. Even when I use just 1 GROUP BY field I get same error. Using query in InformaticaCloud.
ERROR
"the FROM Config_21Cent WHERE resp_ind = 'Insurance' GROUP BY
resp_Ind;;] is empty in JDBC connection:
[jdbc:informatica:sqlserver://cbo-aps-inrpt03:1433;DatabaseName=SalesForce]."
SELECT sum(Cast(Resp_Ins_Open_dol AS decimal(10,2))) as baltotal,
carrier_code,
carrier_name,
carrier_grouping,
collector_name,
dataset_loaded,
docnum,
envoy_payer_id,
loc,
market,
master_payor_grouping,
plan_class,
plan_name,
resp_ins,
resp_ind,
resp_payor_grouping,
Resp_Plan_Type,
rspphone,
state
FROM Config_21Cent
WHERE resp_ind = 'Insurance'
GROUP BY
(resp_ins + resp_payor_grouping +
carrier_code + state + Collector_Name);
Your entire query isn't going to work. The group by statement contains a single expression, the summation of a bunch of fields. The select statement contains zillions of columns without aggregates. Perhaps you intend for something like this:
select resp_ins, resp_payor_grouping, carrier_code, state, Collector_Name,
sum(Cast(Resp_Ins_Open_dol AS decimal(10,2))) as baltotal
from Config_21Cent
WHERE resp_ind = 'Insurance'
GROUP BY resp_ins, resp_payor_grouping, carrier_code, state, Collector_Name;
THis will work in both databases.
The columns in SELECT statement must be a subset (not proper subset but subset) of columns in 'GROUP BY' statement. There is no such restriction on aggregates in SELECT statement though. There could be any number of aggregates; aggregates even on columns not in GROUP BY statement can be included.