I am trying to create a cross tab query and i have written the following query.when i am running it getting an error.so please suggest me right syntax to get cross tab query.
set #sql=null;
select group_concat(distinct concat('sum(case when TX_NAME="',TX_NAME,
'" then sum(FL_AMOUNT) else 0 end ) as ',TX_NAME))into #sql
from cmn_test_bill_x_value ;
set #sq l=con cat('select b.KYS_ID,b.FKYS_CLIENT_ID,',#sql,'
from cmn_bill b left join cmn_patient_bill_details bd
on b.KYS_ID=bd.FKYS_BILL_ID
left join cmn_test_bill_type t
on bd.FKYS_BILL_CATEGORY=t.KYS_ID
left join cmn_test_bill_x_value x
on bd.FKYS_BILL_SUB_CATEGORY=x.KYS_ID
group by x.TX_NAME');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEAL LOCATE PREPARE stmt;
UPDATED: Try
SET #sql = NULL;
SET #month = '2014-02-01';
SELECT GROUP_CONCAT(DISTINCT CONCAT('SUM(CASE WHEN TX_NAME=''', tx_name,
''' THEN fl_amount ELSE 0 END) AS `', tx_name, '`'))
INTO #sql
FROM cmn_test_bill_x_value;
SET #sql = CONCAT('
SELECT b.KYS_ID, b.FKYS_CLIENT_ID, ', #sql, '
FROM cmn_bill b LEFT JOIN cmn_patient_bill_details bd
ON b.kys_id = bd.fkys_bill_id LEFT JOIN cmn_test_bill_type t
ON bd.fkys_bill_category=t.kys_id LEFT JOIN cmn_test_bill_x_value x
ON bd.fkys_bill_sub_category=x.kys_id
WHERE b.date >= ''', #month , '''
AND b.date < ''', #month + INTERVAL 1 MONTH - INTERVAL 1 DAY, '''
GROUP BY x.TX_NAME');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Here is SQLFiddle demo
Related
I Have a table Attendances
and then I Make a Report using this Query
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(case when `tanggal` = ''',
`tanggal`,
''' then `in_time` end) AS `',
`tanggal`, '`'
) ORDER BY `id_employee` ASC SEPARATOR ',\n'
) INTO #sql
FROM `attendances` ;
SET #sql2 = CONCAT('SELECT id_employee, ', #sql, ' FROM attendances GROUP BY id_employee');
PREPARE stmt FROM #sql2;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Output Query :
Question : I Want To Print in_time and out_time after clause then ? Is it Possible ?
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(case when `tanggal` = ''', `tanggal`, ''' then CONCAT(in_time,''-'', out_time) end) AS `', `tanggal`, '`'
) ORDER BY `id_employee` ASC SEPARATOR ',\n'
) INTO #sql
FROM `attendances` ;
SET #sql2 = CONCAT('SELECT id_employee, ', #sql, ' FROM attendances GROUP BY id_employee');
PREPARE stmt FROM #sql2;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have created this query to generate report and its working fine but i want to download the result of this query in .CSV file. How to execute this query in laravel ?
Query :
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when wm.SubPointId = ''',
wm.SubPointId,
''' then Balance else 0 end) AS ',
REPLACE ( ws.SubPointType, ' ', '' )
)
) INTO #sql
FROM wallet_master wm, wallet_subpoints ws WHERE wm.SubPointId = ws.SubPointId;
SET #sql = CONCAT('SELECT MobileNo, ', #sql, ', sum(Balance) as `TotalBalance`
FROM wallet_master wm
GROUP BY MobileNo');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have following tables
demographic_categories
demographic_id demographic_name
1 color
2 age_group
project_tests
test_id group_id project_id
1 1 1
2 1 1
test_demographic_requirements
test_id project_id demgraphic_id demographic_value
1 1 1 blue
1 1 2 young
2 1 1 green
2 1 2 middle
And I need a query which would give me following result :
test_id group_id color age_group
1 1 blue young
2 1 green middle
I guess we need to use concept of pivot table to get the result, but I am unable to. And I demographic categories can we might be same they tend to change so I need something dynamic so what would be the best way to do it ?
I have tried doing the following based of previous similar questions but it doesn't seems to work for me, here is what I have tried:
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when dc.demographic_name = ''',
demographic_name,
''' then trd.demographic_value end) AS ',
replace(demographic_name, ' ', '')
)
) INTO #sql
from demographic_categories;
SET #sql = CONCAT('SELECT pt.test_id, pt.group_id,
', #sql,'
from test_requirement_demographic trd
LEFT JOIN demographic_categories dc ON trd.demographic_id = dc.demographic_id
LEFT JOIN project_tests pt ON pt.test_id = trd.test_id and project_id =1
group by pt.test_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Your dynamic SQL is just fine except for one thing. It has an ambiguous column project_id on your second left join, Just replace it with pt.project_id or trd.project_id and it will give desired result.
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when dc.demographic_name = ''',
demographic_name,
''' then trd.demographic_value end) AS ',
replace(demographic_name, ' ', '')
)
) INTO #sql
from demographic_categories;
SET #sql = CONCAT('SELECT pt.test_id, pt.group_id,
', #sql,'
from test_demographic_requirements trd
LEFT JOIN demographic_categories dc ON trd.demographic_id = dc.demographic_id
LEFT JOIN project_tests pt ON pt.test_id = trd.test_id and pt.project_id =1
group by pt.test_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I ran it on a rextester. Here is the link : dynamic_pivot_test
Hi i've got something like this as part of a more complex query:
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Rather than executing the stmt itself i want to create a table from the result of the execute.
Create table A as select * from (Execute stmt)
gives me error
EDIT:
Here's the entire stuff:
Use catdatabase;
SET SESSION group_concat_max_len = 1000000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN columnA = "' ,columnA, '"THEN 1 ELSE 0 end) AS "' ,columnA, '"'))
INTO #sql
FROM
tableB;
SET #sql = CONCAT('SELECT columnB, Count(*) total, ', #sql, '
FROM tableA inner join tableB on tableA.columnC = tableB.columnE where tableA.columnD <> "catpoop"
GROUP BY columnB');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
As I can see you want to pivot your data and wants to save into temporary table.
I have updated your query, Please check out this:
Use catdatabase;
SET SESSION group_concat_max_len = 1000000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN columnA = "' ,columnA, '"THEN 1 ELSE 0 end) AS "' ,columnA, '"'))
INTO #sql
FROM
tableB;
SET #sql = CONCAT('Create temporary table temp SELECT columnB, Count(*) total, ', #sql, ' FROM tableA inner join tableB on tableA.columnC = tableB.columnE where tableA.columnD <> "catpoop"
GROUP BY columnB');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
If you get any error in this just let me know.
set #table='t2';
SET #table1 = 'test';
set #a = concat('create table ',#table,' select * from ',#table1);
prepare stmt1 from #a;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
https://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html
updated:
SET SESSION group_concat_max_len = 1000000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('SUM(CASE WHEN columnA = "' ,columnA, '"THEN 1 ELSE 0 end) AS "' ,columnA, '"'))
INTO #sql
FROM
tableB;
SET #sql = CONCAT('SELECT columnB, Count(*) total, ', #sql, '
FROM tableA inner join tableB on tableA.columnC = tableB.columnE where tableA.columnD <> "catpoop"
GROUP BY columnB');
set #new_sql = concat ('create table A',#sql);
PREPARE stmt FROM #new_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
My SQLFiddle: http://sqlfiddle.com/#!2/729a9/1
As you can see, despite there being two rows in the table, there is one row returned.
It's also the highest id, so maybe that has something to do with it?
I'm stumped like a log, sorry to say.
SQL:
SELECT GROUP_CONCAT(distinct
CONCAT(
'max(case when `pat`.`name` = ''',
`pat`.name,
''' then `pa`.`value` end) as `',
`pat`.name, '`'
)
) INTO #list
FROM `product_attribute_types` pat;
SET #sql = CONCAT('select ', #list, '
from `products` `p`
LEFT JOIN `product_attributes` `pa`
ON `p`.id=`pa`.`product_id`
LEFT JOIN `product_attribute_types` `pat`
ON `pa`.`type`=`pat`.`id`
');
PREPARE stmt FROM #sql;
EXECUTE stmt;
Firstly: you have had two attributes for the same product_id = 1, change table product_attributes in this way -
INSERT INTO `product_attributes` (`product_id`,`type`,`value`) VALUES
(1,1,'blue'),
(1,2,'shirt'),
(2,1,'green'),
(2,2,'pants');
Then try this one -
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(pat.name = ''', name, ''', pa.value, NULL)) AS ', name
)
) INTO #sql
FROM product_attribute_types;
SET #sql = CONCAT('SELECT pa.product_id, ', #sql, ' FROM product_attributes pa INNER JOIN product_attribute_types pat ON pa.type = pat.id GROUP BY pa.product_id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Result:
+------------+-------+-------+
| product_id | color | name |
+------------+-------+-------+
| 1 | blue | shirt |
| 2 | green | pants |
+------------+-------+-------+
Add WHERE filter if needed.
You're missing a GROUP BY clause in #sql, as well as the product ID that the row refers to.
SET #sql = CONCAT('select p.id, ', #list, '
from `products` `p`
LEFT JOIN `product_attributes` `pa`
ON `p`.id=`pa`.`product_id`
LEFT JOIN `product_attribute_types` `pat`
ON `pa`.`type`=`pat`.`id`
GROUP BY p.id
');
FIDDLE