MySQL Stored Procedure Column Name Join Syntax - mysql

I'm getting all kinds of errors with this stored procedure, from undefined column names to ambiguous field names.
What I'm trying to do is select each subscriber ID where action, share, test, viral, and total are at the highest value. The subscriberID can will be different for each highest value, so you might be returning up to 5 subscriberIDs. Maybe my logic is off here, but below is my code(Please note this is just for the 'action' column):
SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`
FROM `subscribers_points` set1
JOIN
(
SELECT `subscriber_id`, MAX(`action`) AS actionMax
FROM `subscribers_points`
WHERE `year` = _year
AND `month` = _month
GROUP BY `subscriber_id`
) groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE `year` = _year
AND `month` = _month;
^ This resulted in 'Unknown column 'set1.subscriber_id' in 'field list'
This looks correct to me. I don't know what's causing the error.

try this ... without most of the backticks ... you only need the backticks to escape reserved words, etc.
SELECT set1.subscriber_id, set1.action, set1.share, set1.test, set1.viral,
( set1.action + set1.share + set1.test + set1.viral ) AS "total", abuse_flag
FROM subscribers_points set1
JOIN (
SELECT subscriber_id, MAX(`action`) AS actionMax
FROM subscribers_points
WHERE year = _year
AND month = _month
GROUP BY subscriber_id
) as groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE year = _year
AND month = _month;

Use 'as' before groupedAction.
SELECT `set1.subscriber_id`, `set1.action`, `set1.share`, `set1.test`, `set1.viral`, ( `set1.action` + `set1.share` + `set1.test` + `set1.viral` ) AS "total", `abuse_flag`
FROM `subscribers_points` set1
JOIN
(
SELECT `subscriber_id`, MAX(`action`) AS actionMax
FROM `subscribers_points`
WHERE `year` = _year
AND `month` = _month
GROUP BY `subscriber_id`
) as groupedAction
ON set1.subscriber_id=groupedAction.subscriber_id
WHERE `year` = _year
AND `month` = _month;

Related

Trying to concatenate three different rows in mysql

So, I have an attributes table and I'm trying to build a query to concatenate into one column
attributes
------------
id, c_id, key, value
1, 1, 'day', 11
2, 1, 'month', 09
3, 1, 'year', 1999
4, 2, 'day', 14
5, 2, 'month', 11
6, 2, 'year', 2004
And this is the query I wrote,
SELECT
consumer_id,
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_day'),
'_',
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_month'),
'_',
CONCAT(
(SELECT `value` FROM consumer_attributes WHERE `key` = 'select_year'),
'',
''
)
)
) AS dob
FROM consumer_attributes
It throws out
ERROR CODE: 1242 Subquery returns more than 1 row
Can someone help me out?
output I'm trying to achieve
consumer_id, concat
1, 11_09_1999
2, 14_11_2004
SELECT c_id, CONCAT_WS('_',
(SELECT value FROM consumer_attributes a WHERE `key`='day' AND a.c_id = c.c_id),
(SELECT value FROM consumer_attributes a WHERE `key`='month' AND a.c_id = c.c_id),
(SELECT value FROM consumer_attributes a WHERE `key`='year' AND a.c_id = c.c_id)) AS dob
FROM (SELECT DISTINCT c_id FROM consumer_attributes) c;
https://www.db-fiddle.com/f/pB6b5xrgPKCivFWcpQHsyE/14
Try this,
SELECT `c_id`, CONCAT(GROUP_CONCAT(IF(`key` = 'day', `value`, NULL)),'_',GROUP_CONCAT(IF(`key` = 'month', `value`, NULL)),'_',GROUP_CONCAT(IF(`key` = 'year', `value`, NULL))) as dob
FROM `consumer_attributes`
GROUP BY `c_id`
Note: is it select_day or day ? You should change it above query if its different .
You didnt join subqueries with main query with id columns, so it finds more than one rows for each record . It should be ok if the rest is ok :
SELECT
dmy.consumer_id,
concat (
max(ifnull( (SELECT `value` FROM consumer_attributes dd WHERE `key` = 'day' and dd.id = dmy.id) , -1)) ,'_' ,
max(ifnull( (SELECT `value` FROM consumer_attributes mm WHERE `key` = 'month' and mm.id = dmy.id) , -1) ), '_' ,
max(ifnull( (SELECT `value` FROM consumer_attributes yy WHERE `key` = 'year' and yy.id = dmy.id) , -1)) )
FROM consumer_attributes dmy
group by dmy.consumer_id
Another approach (if you have a lot of data you might want to time different answers);
SELECT c_id, CONCAT(d.d, '_', m.m, '_', y.y) dob
FROM (select c_id, value d FROM consumer_attributes WHERE `key`='day') d
NATURAL JOIN (select c_id, value m FROM consumer_attributes WHERE `key`='month') m
NATURAL JOIN (select c_id, value y FROM consumer_attributes WHERE `key`='year') y;

MySQL Attendance Calculation

Here i have table attendances
I need result as shown below
How can i achieve this in mysql without using any programming language
Sql File is Attendances.sql
We can try a pivot query approach, aggregating by user and date:
SELECT
user_id,
DATE(date_time) AS date,
TIMESTAMPDIFF(MINUTE,
MAX(CASE WHEN status = 'IN' THEN date_time END),
MAX(CASE WHEN status = 'OUT' THEN date_time END)) / 60.0 AS hours
FROM yourTable
GROUP BY
user_id,
DATE(date_time);
The caveats of this answer are many. It assumes that there would be only one IN and OUT entry, per user, per day. If a period could cross over dates, then my answer might not generate correct results. Also, if an IN or OUT value be missing, then NULL would be reported for the hours value.
I have Achieve it my self by creating a mysql function and view
Mysql View
CREATE OR REPLACE VIEW `view_attendances` AS
SELECT
`a`.`id` AS `a1_id`,
`a`.`user_id` AS `user_id`,
CAST(`a`.`date_time` AS DATE) AS `date`,
`a`.`date_time` AS `in`,
`a2`.`id` AS `a2_id`,
`a2`.`date_time` AS `out`,
(TIMESTAMPDIFF(SECOND,
`a`.`date_time`,
`a2`.`date_time`) / 3600) AS `hours`
FROM
(`attendances` `a`
JOIN `attendances` `a2` ON (((`a`.`is_confirm` = 1)
AND (`a`.`status` = 'IN')
AND (`a2`.`id` = FN_NEXT_OUT_ATTENDANCE_ID(`a`.`user_id`, `a`.`date_time`, `a`.`status`))
AND (a2.status = 'OUT')
AND (CAST(`a`.`date_time` AS DATE) = CAST(`a2`.`date_time` AS DATE)))))
Mysql Function
CREATE FUNCTION `fn_next_out_attendance_id`( _user_id INT, _attendance_date_time DATETIME, _status VARCHAR(10) ) RETURNS int(11)
BEGIN
DECLARE _id INT(11);
SELECT
id INTO _id
FROM
attendances
WHERE
is_confirm = 1
AND user_id = _user_id
AND date_time > _attendance_date_time
AND `status` <> _status
ORDER BY
date_time ASC LIMIT 1 ;
RETURN if (_id IS NULL, 0, _id);
END

Error GROUP BY Dates MysQL

I am trying to group by dates 2 different tables. However, something is going wrong as I am not able to group by dates.
I have 2 tables First "Budget" and Second "Sales Performance By Region"
The Idea is to show the Budget for all the months (12 months)
and each month we have data we will see the Sales for each specific month.
SELECT
BB.RG,
BB.YEAR,
DATE_FORMAT( BB.MONTH, '%M' ) AS `MONTH`,
SPR.Bookings,
SPR.`Bookings PY`,
SPR.Billing,
SPR.`Billing PY`,
SPR.`GP Amt`,
SPR.`GP Amt PY`,
SUM( BB.BUDGET ) AS BUDGET
FROM
BRANCH_BUDGET BB
LEFT JOIN Sales_Performance_Region SPR
ON BB.MONTH = SPR.MONTH
WHERE
BB.RG = 'FE'
AND SPR.RG = 'FE'
AND BB.YEAR = '2018'
GROUP BY
BB.MONTH
Above you can see the code. Instead of showing the 12 Months due to I only have data for 2 Months is showing January and February.
I hope the question makes sense. Can you guide me?
Whenever you invoke a GROUP BY after a WHERE statement or any other aggregate function inside a SELECT statement you will need to treat everything inside the select statement as an aggregate, otherwise you will face problems:
In your code:
SELECT `BRANCH_BUDGET`.`RG` ,
`BRANCH_BUDGET`.`YEAR` AS `YEAR` ,
`DATE_FORMAT( `BRANCH_BUDGET`.`MONTH` , '%M' ) AS `MONTH` ,
`Sales_Performance_Region`.`Bookings` ,
`Sales_Performance_Region`.`Bookings PY` ,
`Sales_Performance_Region`.`Billing` ,
`Sales_Performance_Region`.`Billing PY` ,
`Sales_Performance_Region`.`GP Amt` ,
`Sales_Performance_Region`.`GP Amt PY` ,
SUM( `BRANCH_BUDGET`.`BUDGET` ) AS `BUDGET`
FROM (
`BRANCH_BUDGET`
LEFT JOIN `Sales_Performance_Region` ON ( `BRANCH_BUDGET`.`MONTH` =
`Sales_Performance_Region`.`MONTH` )
)
WHERE `BRANCH_BUDGET`.`RG` = 'FE'
AND `Sales_Performance_Region`.`RG` = 'FE'
AND `BRANCH_BUDGET`.`YEAR` = '2018'
GROUP BY `BRANCH_BUDGET`.`MONTH`
You only group by BRANCH_BUDGET.MONTH, but do not group by any other column or perform an aggregate function on any other column (save BRANCH_BUDGET.BUDGET). Thus your output is faulty in that it only returns two months.
First thanks for the comments I want to post the result in case someone is interested.
The issue was: I didn't join the Region (RG) from both tables. So the result should look like the code below:
SELECT `BRANCH_BUDGET`.`RG` ,
`BRANCH_BUDGET`.`YEAR` AS `YEAR` ,
DATE_FORMAT( `BRANCH_BUDGET`.`MONTH` , '%M' ) AS `MONTH` ,
`Sales_Performance_Region`.`Bookings` ,
`Sales_Performance_Region`.`Bookings PY` ,
`Sales_Performance_Region`.`Billing` ,
`Sales_Performance_Region`.`Billing PY` ,
`Sales_Performance_Region`.`GP Amt` ,
`Sales_Performance_Region`.`GP Amt PY` ,
SUM( `BRANCH_BUDGET`.`BUDGET` ) AS `BUDGET`
FROM (
`BRANCH_BUDGET`
LEFT JOIN `Sales_Performance_Region`
ON ( `Sales_Performance_Region`.`MONTH` = `BRANCH_BUDGET`.`MONTH` )
AND ( `Sales_Performance_Region`.`RG` = `BRANCH_BUDGET`.`RG` )
)
WHERE `BRANCH_BUDGET`.`RG` = 'FE'
AND `BRANCH_BUDGET`.`YEAR` = '2018'
GROUP BY `BRANCH_BUDGET`.`MONTH`

Select in Concat mysql

I'm trying to get a date value with:
- Current year
- Current month
- Day number from one select
the query
SELECT rat_data FROM rate_unita WHERE rateid = 1
as a result one INT value.
When I try to execute the following:
SELECT DATE(CONCAT(YEAR(NOW())),(MONTH(NOW())), (SELECT rat_data FROM rate_unita WHERE rateid = 1))
Mysql mark my syntax as incorrect near ' ( MONTH( NOW( ) ) ) , ( SELECT rat_data FROM rate_unita WHERE r
I think that there is something wrong with the way I'm calling the SELECT in the CONCAT, what is the correct query to reach my goal?
Thanks
L
You're closing the concat function too early. Remove some extra parentheis
SELECT DATE(CONCAT(YEAR(NOW()),
MONTH(NOW()),
(SELECT rat_data FROM rate_unita WHERE rateid = 1)
))
But you need to add some hyphens to make it a true date value
SELECT DATE(
CONCAT(
YEAR(NOW()),
'-',
MONTH(NOW()),
'-',
(SELECT rat_data FROM rate_unita WHERE rateid = 1)
)
)
This should result in a date of YEAR-MONTH-rat_data
Here's a working SQL Fiddle
Use DATE_FORMAT function. Here are a few examples:
http://www.w3schools.com/sql/func_date_format.asp
http://www.mysqltutorial.org/mysql-date_format/

Pivot With Calendar Table

I am trying to pivot this data but I am getting an error of
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.
Highlighting the comma after SUM([Total Count]) but it has to be there, what should I change so my query executes properly?
select *
FROM
(
select a.regionalLocale As [RL],
Count(ID) As [Total Count],
CONVERT(VARCHAR(20), dt.week) AS Week
FROM database14.dataTable a
INNER JOIN calendarDB.masterCalendar dt
ON a.SaleDate = dt.FullDate
WHERE a.SaleDate IS NOT NULL
) src
pivot
(
SUM([Total Count]), [RL]
For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv
You've got a few issues with your query.
One you've got the syntax SUM([Total Count]), [RL] in your PIVOT. You only want to include the column you are aggregating here.
Second, there is no need to use count(id) inside your subquery, let the PIVOT aggregation handle the total. Change your code to:
select [RL],
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]
FROM
(
select a.regionalLocale As [RL],
ID,
CONVERT(VARCHAR(20), dt.week) AS Week
FROM database14.dataTable a
INNER JOIN calendarDB.masterCalendar dt
ON a.SaleDate = dt.FullDate
WHERE a.SaleDate IS NOT NULL
) src
pivot
(
COUNT(ID)
For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv