Please some one help me tI have two Tables in my MYSQL database,
the first table - (Employee Table) consists of
EmployeeNo| EmployeeName
the second table - (Attendance table) consists of
DATE | TIME | STATUS| EmployeeNo
and a calendar table that holds only date for every month
I want to generate attendance sheet similar to this
Click here
I end up writing the following SQL, but it gives me syntax error
#1064 - 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 'from (select cal.calendarDate,
emp.first_name,emp.nu' at line 2
and my query ,
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(CASE WHEN calemp.calendarDate = ''',date_format(calendarDate, '%Y-%m-%d'),''' THEN coalesce(att.inorout, ''P'') END) AS `',date_format(calendarDate, '%Y-%m-%d'), '`'
)
) INTO #sql
FROM yearly_date_calendar
where calendarDate >= '2016-11-01'
and calendarDate <= '2016-11-30';
SET #sql = CONCAT('SELECT calemp.first_name,calemp.nurse_code,',#sql,'
from
(
select cal.calendarDate,emp.first_name,emp.nurse_code
from yearly_date_calendar cal
cross join syscare_caregiver emp
) calemp
left join syscare_employee_attendance att
on calemp.nurse_code = att.emp_code
and calemp.calendarDate = att.attendance_date
where calemp.calendarDate>=''2016-11-01''
and calemp.calendarDate <= ''2016-11-30''
group by calemp.first_name, calemp.nurse_code,calemp.calendarDate
');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You can use below query and fetch all database result
select EmployeeTable.EmployeeNo,Employee Table.EmployeeName,Attendance table.DATE,Attendance table.TIME,Attendance table.STAUS,Attendance table.EmployeeNo from Employee Table INNER JOIN Attendance table ON
EmployeeTable.EmployeeNo=Attendance table.EmployeeNo
Related
I apologize in advance, I'm not good at sql.
I want to do something very simple in a sql procedure but I'm stuck :
SELECT donnee.id_enregistrement, ',#col_createur, #col_date_creation, #col_date_derniere_modification, #COLUMNS
FROM ta_donnee_champ donnee
In the variable #COLUMNS there is a list of id, that I search in the table "ta_donnee_champ donnee".
I also want to use the same list of id to search in another table in the same query.
How can I put that in an inner join?
Like something like this :
SELECT donnee.id_enregistrement, ',#col_createur, #col_date_creation, #col_date_derniere_modification, #COLUMNS,'
FROM ta_donnee_champ donnee
INNER JOIN ta_champ_tableau ct
ON ct.id_champ_colonne IN (#COLUMNS)
Can someone give me a simple explanation please?
******************************EDIT********************************
In this procedure #COLUMNS represents columns of the desired results.
To these columns, I need to add values, the following code works :
IF #COLUMNS IS NOT NULL THEN
SET #SQL = CONCAT(
'SELECT donnee.id_enregistrement, ',#col_createur, #col_date_creation, #col_date_derniere_modification, #COLUMNS,'
FROM ta_donnee_champ donnee
INNER JOIN t_enregistrement enregistrement
ON donnee.id_enregistrement = enregistrement.id_enregistrement
WHERE donnee.id_enregistrement IN (',IFNULL(p_id_enregistrement, 'donnee.id_enregistrement'),')
AND donnee.id_enregistrement in (
select DISTINCT id_enregistrement from ta_participant
where id_groupe = ', p_id_groupe,'
or id_groupe in (
select id_groupe_lu
from ta_droits_groupe
inner join t_groupe on ta_droits_groupe.id_groupe_lu = t_groupe.id_groupe
where id_groupe_lecteur = ', p_id_groupe,'
and t_groupe.id_application = ', p_id_application,'
)
)
GROUP BY donnee.id_enregistrement'
);
-- Prépare et exécute la requête
PREPARE stmt FROM #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
My question is : I need to add another table from which I must know that ids are inside. How do I proceed best to search not only for id's in ta_donnee_champ donnee but also in another table?
How is #COLUMNS set :
SET #COLUMNS = NULL;
IF p_autoriser_tableau = 1 THEN
SET #filtre = 'SELECT DISTINCT id_champ_colonne FROM ta_champ_tableau';
ELSE
SET #filtre = 'SELECT DISTINCT id_champ_tableau AS id_champ FROM ta_champ_tableau UNION SELECT DISTINCT id_champ_colonne FROM ta_champ_tableau';
END IF;
-- Construit les colonnes à horizontaliser
SET #SQL1 = CONCAT('
SELECT GROUP_CONCAT(
DISTINCT CONCAT(
\'GROUP_CONCAT(IF(donnee.id_champ = \',
champ.id_champ ,
\', donnee.valeur, NULL)) AS `\',
champ.id_champ,\'`\'
)ORDER BY onglet.ordre, section.ordre, champ.ordre
) INTO #COLUMNS
FROM t_champ champ
INNER JOIN t_section section
ON section.id_section = champ.id_section
INNER JOIN t_onglet onglet
ON onglet.id_onglet = section.id_onglet
INNER JOIN ta_droits_champ droits_champ
ON droits_champ.id_groupe IN (
SELECT id_groupe FROM ta_agent_groupe WHERE id_agent = ', p_id_agent,'
)
AND droits_champ.id_champ = champ.id_champ
where onglet.id_application IN (', p_id_application,')
AND droits_champ.voir = 1
AND champ.id_champ NOT IN (',#filtre,')
AND
(
champ.date_fin_validite IS NULL
OR
date_format(champ.date_fin_validite, "%Y-%m-%d") > COALESCE(str_to_date("', p_date_validite,'", "%d/%m/%Y"), "01/01/1900")
)
;');
PREPARE stmt FROM #SQL1;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have the following stored procedure setup and it has just stopped working in the last few days. Does anyone know why this could just stop working? None of the database tables have changed.
drop procedure if exists bookings_by_voucher;
delimiter //
create procedure bookings_by_voucher(in start_date date, in end_date date, l_id int)
language sql
deterministic
sql security definer
begin
declare s text;
select distinct group_concat(concat('sum(if(c.gross_value = ',gross_value,',c.net_value,0)) coupon',
cast(gross_value as unsigned))) from coupons into s;
set #query = concat('select ',if(l_id is null, '"All Locations"','l.location_name'),
' location_name,ifnull(b.places, 0) as places, ',
if(start_date is null and end_date is null,'"All Dates"',
if(start_date is null, concat('" <= ',end_date,'"'),
if(end_date is null,concat('" >= ',start_date,'"'),
concat('"',start_date,' - ',end_date,'"')
)
)
),' dates,',
ifnull(s,'"No Coupons"'),
',round(sum(b.price/1.2-ifnull(c.net_value,0)), 2) paidbycard from locations l join bookings b ',
' on l.id = b.location_id ',
concat(if(start_date is null,'',concat(' and b.date >= "', start_date,'"'))),
concat(if(end_date is null,'',concat(' and b.date <= "', end_date,'"'))),
' left join coupons c on b.voucher_code = c.code',
if (l_id is null, ' group by l.id', concat(' where l.id = ', l_id) ));
/*select #query;*/
prepare stmt from #query;
execute stmt;
end//
The error that I am getting back from my application (built in Laravel 5.1) is:
SQLSTATE[42000]: Syntax error or access violation: 1064 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 'paidbycard
from locations l join bookings b on l.id = b.location_id left join
' at line 1 (SQL: call bookings_by_voucher(null, null, null))
I have found something, If I am not wrong, after your "group by" clause there is "where" clause.
I am using IBatis and Spring framework.
I would like to execute multi queries but I could not get the response.
<select id="getUIs" resultMap="blpUiVOMap" parameterClass="Map">
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('COUNT(CASE WHEN bug.BUG_STT = ', STT_ID, ' THEN 1 END) AS ''bugI', STT_ID, '''')
) INTO #sql
from BLP_STT <![CDATA[;]]>
SET #sql = CONCAT('SELECT ui.UI_ID, ui.UI_NM, cat.CAT_ID, cat.CAT_NM, cat.PRNT_ID, cat1.CAT_NM as PRNT_NM,',#sql,'FROM BLP_UI ui JOIN BLP_CAT cat ON ui.CAT_ID = cat.CAT_ID JOIN BLP_CAT cat1 ON cat.PRNT_ID = cat1.CAT_ID JOIN BLP_BUG bug ON ui.UI_ID = bug.UI_ID JOIN BLP_STT stt ON bug.BUG_STT = stt.STT_ID WHERE 1 = 1 GROUP BY ui.UI_ID ORDER BY ui.UI_ID ASC') <![CDATA[;]]>
PREPARE stmt FROM #sql <![CDATA[;]]>
EXECUTE stmt <![CDATA[;]]>
DEALLOCATE PREPARE stmt <![CDATA[;]]>
</select>
In MySQL, this query is working fine.
The <select> will create a single PreparedStatement in JDBC. You are trying to execute commands from the MySQL command line. This won't work in JDBC or MyBatis.
You will need to create a single query that combines all your strings. Maybe something like this?
SELECT ui.UI_ID, ui.UI_NM, cat.CAT_ID, cat.CAT_NM, cat.PRNT_ID, cat1.CAT_NM as PRNT_NM,
(SELECT
GROUP_CONCAT(DISTINCT
CONCAT('COUNT(CASE WHEN bug.BUG_STT = ', STT_ID, ' THEN 1 END) AS ''bugI', STT_ID, '''')
)
from BLP_STT
)
FROM BLP_UI ui JOIN BLP_CAT cat ON ui.CAT_ID = cat.CAT_ID JOIN BLP_CAT cat1 ON cat.PRNT_ID = cat1.CAT_ID JOIN BLP_BUG bug ON ui.UI_ID = bug.UI_ID JOIN BLP_STT stt ON bug.BUG_STT = stt.STT_ID WHERE 1 = 1 GROUP BY ui.UI_ID ORDER BY ui.UI_ID ASC')
Note, you also do not need to put a ; in the XML either.
I have a SQL query which gives the correct result, but performs too slow.
The query operates on the following three tables:
customers contains lots of customer data like name, address, phone
etc. To simplify the table i am only using the name.
customdatas contains certain custom (not customer) data. (The
tables are created in software, which is why the plural form is wrong
for this table)
customercustomdatarels associates custom data with a customer.
customers
Id Name (many more columns)
-----------------------------------------------------------------------
8053c6f4c5c5c631054ddb13d9186117 MyCustomer ...
2efd2aa5711ddfade1f829b12dd88cf3 CheeseFactory ...
customdata
id key
-------------------------------------------------
22deb172c1af6e8e245634a751871564 favoritsport
86eea84d296df9309ad6ff36fd7f856e favoritcheese
customercustomdatarels (relation between customer and custom data - with corresponding value)
customer customdata value
-------------------------------------------------------------------------------------
8053c6f4c5c5c631054ddb13d9186117 22deb172c1af6e8e245634a751871564 cycling
8053c6f4c5c5c631054ddb13d9186117 86eea84d296df9309ad6ff36fd7f856e cheddar
2efd2aa5711ddfade1f829b12dd88cf3 22deb172c1af6e8e245634a751871564 football
2efd2aa5711ddfade1f829b12dd88cf3 86eea84d296df9309ad6ff36fd7f856e mouldy
What i want is a table basically consisting of all data in customers with an variable amount of extra columns, corresponding to the custom data specified in customercustomdatarels.
These columns should be defined somewhere and I have therefore created the following table which defines such extra columns and maps them to a key in the customdata table:
test_customkeymapping
colkey customkey
---------------------
1 favoritsport
2 favoritcheese
The result should then be:
Name ExtraColumn_1 ExtraColumn_2
---------------------------------------------
CheeseFactory football mouldy
MyCustomer cycling cheddar
(ExtraColumn_1 is therefore synonym for a customers' favorite sport and ExtraColumn_2 is a synonym for a customers' favorit cheese.)
This result is achieved by executing the following query:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE
WHEN ckm.colkey = ', colkey, ' THEN
(SELECT value FROM customercustomdatarels ccdr2
LEFT JOIN customdatas cd2
ON cd2.id = ccdr2.customdata
WHERE cd2.key = ckm.customkey AND c.Id = ccdr2.customer)
END) AS ', CONCAT('`ExtraColumn_', colkey, '`'))
) INTO #sql
FROM test_customkeymapping;
SET #sql = CONCAT('SELECT c.Name, ', #sql, '
FROM customers c
LEFT JOIN customercustomdatarels ccdr
ON c.Id = ccdr.customer
LEFT JOIN customdatas cd
ON cd.Id = ccdr.customdata
LEFT JOIN test_customkeymapping ckm
ON cd.key = ckm.customkey
GROUP BY c.Id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
This works. But is too slow (for 7000 customers it takes ~10 seconds).
The query was greatly influenced by the solution in this question:
MySQL Join Multiple Rows as Columns
How do I optimize this query?
I don't understand why you are using a subquery in the group_concat() statement. Wouldn't this generate the code that you really want to run?
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN ckm.colkey = ', colkey, ' THEN ccd.value END) AS ',
CONCAT('ExtraColumn_', colkey, ''))
) INTO #sql
FROM test_customkeymapping;
SET #sql = CONCAT('SELECT c.Name, ', #sql, '
FROM customers c
LEFT JOIN customercustomdatarels ccdr
ON c.Id = ccdr.customer
LEFT JOIN customdatas cd
ON cd.Id = ccdr.customdata
LEFT JOIN test_customkeymapping ckm
ON cd.key = ckm.customkey
GROUP BY c.Id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
Note: This is untested, but the idea is the same. Use the values from the main from statement for your work rather than the values from some extra, unnecessary subquery.
I'm trying to pivotise my columns to get from rows to tables.
It's working like expected with the code I have now, but when my fields get updated I have to manually edit the query in order to update it.
I'm trying to automate the process but I'm not getting it to work. Any ideas?
This is the manual code which works:
SELECT
md.entity_guid AS guid, username, e.time_created, time_updated, e.enabled, banned,e.last_action, last_login,
MAX(IF(msn.string = 'question1', msv.string, NULL)) AS question1
FROM exp_metadata md
JOIN exp_metastrings msn ON md.name_id = msn.id
JOIN exp_metastrings msv ON md.value_id = msv.id
JOIN exp_users_entity u ON u.guid = md.entity_guid
JOIN exp_entities e ON e.guid = md.entity_guid
GROUP BY
guid
And this is the query I'm trying to do to automate it:
SET #sql = NULL;
SELECT
md.entity_guid AS guid, username, e.time_created, time_updated, e.enabled, banned, e.last_action, last_login,
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(msn.string = ''',
msn.string,
''', msv.string, NULL)) AS ',
msn.string
)
) INTO #sql
FROM exp_metadata md
JOIN exp_metastrings msn ON md.name_id = msn.id
JOIN exp_metastrings msv ON md.value_id = msv.id
JOIN exp_users_entity u ON u.guid = md.entity_guid
JOIN exp_entities e ON e.guid = md.entity_guid
SET #sql = CONCAT('SELECT e.guid, ', #sql, ' FROM exp_entities e GROUP BY e.guid');
I get an error in phpmyadmin about the last line.
When I delete the last line to see if it does anything, I get:
#1222 - The used SELECT statements have a different number of columns
Any help would be appreciated.
Thanks a lot, Dries