Mysql SUM and group by no working - mysql

I have just started a new question to make this a bit more clear.
I have just migrated from MS SQL to MySQL this query worked in MS SQL
This is rstCombinedChartData
Then the result which should have 2 column 'yes' and 'no' with values for some reason on mysql I'm getting just one and itemcolumn false.
As you can see for some reason it's adding up all the results giving 551 where it should be like this:
Yes x
No x
Why?
This is the SQL Query:
SELECT
itemColumn
,SUM(valueColumn) AS valueColumn
,label
FROM
rstCombinedChartData
GROUP BY
label
,itemColumn
ORDER BY
label DESC
,itemColumn DESC

Plase try:
SELECT itemColumn, SUM(CAST(valueColumn AS SIGNED)), label FROM rstCombinedChartData GROUP BY label, itemColumn ORDER BY label DESC, itemColumn DESC

Related

SQL Query correction required

SELECT TOP (2)
DATEPART(HOUR,t.callerDateTime) as Hour
,count(cli) as Count
FROM ivrtimeout t
where convert(date,t.callerDateTime) = convert(date,getdate(),103)
group by DATEPART(HOUR,t.callerDateTime)
order by DATEPART(HOUR,t.callerDateTime) desc
Above Query is working fine in case of Microsoft SQL Server and giving error using in xamp server maria-db.
Can anyone please make correction?
Try this:
select
extract(HOUR from callerDateTime) as Hour,
count(cli) as Count
from ivrtimeout
where callerDateTime >= timestamp(current_date)
group by 1
order by 1 desc
limit 2

how to use DISTINCT ON with mysql using ActiveRecord

Want all the latest visit of all the distinct user.
For this I am using below query
Event.order(time: :desc).select('DISTINCT ON(user_id) user_id, time')
Getting SQL syntax error.
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC ' at line 1: SELECT DISTINCT ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC LIMIT 11)
events table column names
["id", "visit_id", "user_id", "name", "properties", "time"]
can anyone help me out in this
Expected output something like this
{ 21 => "2018-12-18 09:44:59", 42 => "2018-12-19 12:08:59"}
21 is user_id and value is last visit time
Using mysql as database
So you want all user visits with last visited time.
Instead of use DISTINCT function, you can use GROUP with MAX function.
Query looks like
Events.group(:user_id).maximum(:time)
This Outputs your desired results
{21=>Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23=>Thu, 20 Dec 2018 06:42:10 UTC +00:00}
Hope this works for you.
FYI
DISTINCT ON(columns). is PostgreSQL Syntax.
Like i said in the comments DISTINCT ON(column), * is PostgreSQL SQL syntax.
The query below you need to have to rewrite in MySQL
SELECT
DISTINCT ON(user_id) AS user_id, time
FROM
<table>
ORDER BY
time DESC
LIMIT 11
The most easy to do that is using SUBSTRING_INDEX(GROUP_CONCAT(..)).
The queries below should give you the correct results.
SET SESSION group_concat_max_len = ##max_allowed_packet;
SELECT
user_id
, SUBSTRING_INDEX(
GROUP_CONCAT(time
ORDER BY
time DESC
)
, ','
, 1
) AS time
FROM
<table>
GROUP BY
user_id
ORDER BY
time DESC
LIMIT 11

How do I aggregate with group by in mysql withou setting sql mode?

This query gets the output I want. In order to run it I have to run
SET sql_mode = '';
Because otherwise I get an error:
SELECT list is not in GROUP BY clause and contains nonaggregated column 'knownLoss.t1.loss' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
SELECT
t1.klDate AS LDate
, t1.Category
, t1.reason AS Reason
, sum(t1.loss) AS Loss
, round(t1.loss / t2.loss,2) AS Percentage
FROM
deptkl t1
JOIN (
SELECT
Store
, sum(loss) AS loss
FROM
deptkl
WHERE
klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
Store = 19
AND
Department = 80
) t2 ON t1.Store = t2.Store
WHERE
klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
t1.Store = 19
AND
Department = 80
GROUP BY
klDate
, Category
, reason
When I place this into the Dataset and Query Dialog of Jasper Studio, I get the same error and I am unable to use the SET sql_mode = ''; command. Any thoughts? If there is a way to achieve this without using SET sql_mode = '';?
I'm guessing the error is from this line in your select:
round(t1.loss / t2.loss,2) AS Percentage
Since you GROUP BY clause does not include this column it's somewhat of a coin toss which t1.loss and t2.loss values will be used. In some cases those values happen to always be the same based on your criteria and so you get the correct results regardless, but the db will still complain since it's being asked to return somewhat arbitrary results for those columns. One way to deal with this would be to simply apply an aggregate function to the columns in question like this:
round(min(t1.loss) / min(t2.loss),2) AS Percentage
or...
round(avg(t1.loss) / avg(t2.loss),2) AS Percentage
I think you want to do this :
round(sum(t1.loss / t2.loss)/count(*),2) AS Percentage
this will calculate the sum of the average loss for every records in the result then divide it on the the count of the record of the group it's like average of average.
EDITS:
sorry i made a syntax error now ,it should give the th wanted result and the error is because you are not using aggregate function on a column that is not in group by clause

Access Query for TopN by Group

I've reviewed quite a bit of the sites (e.g. Allen Brown) for creating a query that produces top 5 (or N) values by group. I think I am getting hung up on the creation of a subquery because I'm referencing a previous query not a table.
I have a query started which counts by month the number of PIs (qryPICountbyMonth). Currently the below gives a data mismatch expression error:
SELECT qryPI.EventMonth, qryPI.PI_Issue, Count(qryPI.PI_Issue) AS
CountOfPI_Issue
FROM qryPI
GROUP BY qryPI.EventMonth, qryPI.PI_Issue
HAVING (((Count(qryPI.PI_Issue)) In (Select Top 5 [PI_Issue] From [qryPI]
Where [EventMonth]=[qryPI].[EventMonth] Order By [PI_Issue] Desc)))
ORDER BY qryPI.EventMonth DESC , Count(qryPI.PI_Issue) DESC;
It is built off a a separate query, qryPI
SELECT tblPI.EventDate, Format([EventDate],'yyyy-mm',1,1) AS EventMonth, tblPI.PI_Issue
FROM tblPI
WHERE (((tblPI.EventDate) >= #4/1/2016# And (tblPI.EventDate) <= #5/31/2016#))
GROUP BY tblPI.EventDate, Format([EventDate],'yyyy-mm',1,1), tblPI.PI_Issue;
I'm hoping to have it generate the top 5 counts of PI_Issue by EventMonth. If I haven't provided enough info let me know.
The problem (or at least a problem) is with [EventMonth]=[qryPI].[EventMonth]. Both your primary source and your lookup are called qryPI. You have to alias at least one of them.
You can't do this:
HAVING (((Count(qryPI.PI_Issue)) In (Select Top 5 [PI_Issue] From [qryPI]
count(field) will return an integer, not the set of values you're counting
I thought you could specify TopN in an Access query (it's in the properties), but you have to specify an order by clause, so it knows how to determine the TOP.
Have you tried:
SELECT top 5
tblPI.EventDate, Format([EventDate],'yyyy-mm',1,1) AS EventMonth, tblPI.PI_Issue
FROM tblPI
WHERE (((tblPI.EventDate) >= #4/1/2016# And (tblPI.EventDate) <= #5/31/2016#))
GROUP BY tblPI.EventDate, Format([EventDate],'yyyy-mm',1,1), tblPI.PI_Issue
order by PI_Issue
also not sure why you're using GROUP BY in your inner query as you're not returning any aggregate functions. Do you just need DISTINCT instead?
try:
SELECT distinct top 5
tblPI.EventDate, Format([EventDate],'yyyy-mm',1,1) AS EventMonth, tblPI.PI_Issue
FROM tblPI
WHERE (((tblPI.EventDate) >= #4/1/2016# And (tblPI.EventDate) <= #5/31/2016#))
order by PI_Issue
Actually, if I understand what you want, you need that GROUP BY instead of DISTINCT, but you also need to return the COUNT(*):
SELECT
Year([eventDate]) AS yr,
Month([eventDate]) AS mo,
tblPI.PI_issue,
Min(tblPI.eventDate) AS MinOfeventDate,
Max(tblPI.eventDate) AS MaxOfeventDate,
Count(tblPI.PI_issue) AS CountOfPI_issue
FROM tblPI
WHERE
(((tblPI.EventDate)>=#4/1/2016# And
(tblPI.EventDate)<#6/1/2016#))
GROUP BY
Year([eventDate]),
Month([eventDate]),
tblPI.PI_issue;
then you want to apply the TOPN function to cnt_issue in an outer query:
SELECT TOP 5 from qryInner
order by cnt_issue desc
except that TOP5 applies to all the query results, not the results grouped by yy/mm, which is what I'm assuming you want, so try this:
SELECT TOP 5
qry_inner.yr,
qry_inner.mo,
qry_inner.CountOfPI_issue,
qry_inner.PI_issue,
qry_inner.MinOfeventDate,
qry_inner.MaxOfeventDate
FROM qry_inner
ORDER BY qry_inner.CountOfPI_issue DESC;
As far as I know, Access doesn't allow you to select the top number of rows within a group, so you'll need to limit your outer query results to one month, then apply the TOP function.

mysql using calculated column at where/having

i have an question how to use an "alias" column at the where/having clause. I know there are some question with an related topic. But I search trough the web and on stackoverfolw and doesn't find an solution.
So i hope for help at this way..
The following statement works well:
SELECT PHRASE,COUNT(*) AS A
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
GROUP BY PHRASE ORDER BY A DESC
LIMIT 16;
PHRASE and TIMESTAMPare columns at the table.
The code selects the top 16 PHRASES, which are inserts by users on the last 7 days.
There are also exist an column USER and so i like now to select the top 16 phrases which are inserted by more than one user.
So i tried this:
SELECT PHRASE,COUNT(*) AS A, COUNT(DISTINCT(USER)) AS B
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
AND B>1
GROUP BY PHRASE ORDER BY A DESC
LIMIT 16;
On other questions on stackoverflow i fond the info, that i have to use HAVING
SELECT PHRASE,COUNT(*) AS A, COUNT(DISTINCT(USER)) AS B
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
GROUP BY PHRASE ORDER BY A DESC
HAVING B>1
LIMIT 16;
But this returns an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HAVING B>1
LIMIT 16' at line 5
I have no idea, how the right syntax could be.
Hope for any kind of help here.
Thank you!
Place the ORDER BY A DESC after Having clause.
SELECT phrase,
Count(*) AS A,
Count(DISTINCT( user )) AS B
FROM my_statistics
WHERE timestamp > Now() - INTERVAL 7 day
GROUP BY phrase
HAVING b > 1
ORDER BY a DESC
LIMIT 16;