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
Related
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
I have the following DB structure:
cars:
id
make
features:
id
name
cars_feature:
id
car_id
feature_id
value
I want to be able to select all cars with all features and return results with feature.name as the column name and cars_feature.value as the value. Right now I am able to get all feature and all values but I only figured out how to do that with group_concat.
What I am looking for is the following output:
car_id car_make color wheels doors
1 Ford blue alloy
2 Audi alloy 3
Data example: SQLFiddle
The following is a modified version of code that I found at Combine multiple rows into one row MySQL.
SET #sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT(
'MAX(CASE WHEN `name` = ''',
`name`,
''' THEN value END) AS `',
`name`, '`'
)
) INTO #sql
FROM (SELECT name,
value
FROM features, car_feature
WHERE features.id = car_feature.feature_id) AS car_features_feature;
SET #sql = CONCAT('SELECT car_feature.car_id AS car_id,
cars.make AS car_make,
',
#sql,
'
FROM car_feature
LEFT JOIN cars ON car_feature.car_id = cars.id
LEFT JOIN features ON car_feature.feature_id = features.id
GROUP BY car_id;');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Thank you for the learning experience.
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
I would like to sort my columns in pivot table. Here is a link to my example table and query what i have now. As you can see in result the name of the columns are unsorted.
I'm basically doing this:
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN DATE(date) = ''', date,
''' THEN score END) `', DATE_FORMAT(date,'%d.%m.%Y'), '`'))
INTO #sql
FROM tabletest
ORDER BY date;
SET #sql = CONCAT('SELECT name,', #sql, '
FROM tabletest
GROUP BY name');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
My column output is like this:
| NAME | 30.11.2013 | 28.11.2013 | 27.11.2013 | 29.11.2013 |
|---------|------------|------------|------------|------------|
| Adele | 234 | 552 | (null) | (null) |
And I would like to have the columns sorted.
Thanks in advance.
Just add an ORDER BY date inside the GROUP_CONCAT:
SELECT GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE WHEN DATE(date) = ''', date,
''' THEN score END) `', DATE_FORMAT(date,'%d.%m.%Y'), '`')
ORDER BY date)
Hi I have a table that looks like this
dt ticker open
1 A 1
1 B 3
2 A 1.1
2 B 2.5
I would need the result to look like
dt A B
1 1 3
2 1.1 2.5
My current query I have included below gets me
dt A B
1 1 NULL
1 NULL 3
2 1.1 NULL
2 NULL 2.5
if anyone could help me out that would be very much appreciated
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'(IF(ticker = ''',
ticker,
''', open, NULL)) AS ''',
ticker,''''
)
) INTO #sql
FROM
prices;
SET #sql = CONCAT('SELECT dt, ', #sql, ' FROM prices');
-- SET #sql = CONCAT('SELECT dt, ', #sql, ' FROM prices GROUP BY dt');
PREPARE stmt FROM #sql;
EXECUTE stmt;
One way to get the result would be:
SELECT t.dt
, MAX(IF(t.ticker='A',t.open,NULL)) AS A
, MAX(IF(t.ticker='B',t.open,NULL)) AS B
FROM mytable t
GROUP BY t.dt
(In MySQL the MAX aggregate can actually be omitted, thought an aggregate is required in other DBMS.)
SELECT t.dt
, IF(t.ticker='A',t.open,NULL) AS A
, IF(t.ticker='B',t.open,NULL) AS B
FROM mytable t
GROUP BY t.dt
Another approach:
SELECT t.dt
, t.open AS A
FROM mytable t
LEFT
JOIN (SELECT s.dt
, t.open AS B
FROM mytable s
WHERE s.ticker = 'B'
GROUP BY s.dt
) b
ON b.dt = t.dt
WHERE t.ticker = 'A'
GROUP BY t.dt
ORDER BY t.dt
You need to add Max to your Group_Concat, Try this
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'Max(case when ticker = ''',
ticker,
''' then open end) AS ',
replace(ticker, ' ', '')
)
) INTO #sql
from prices;
SET #sql = CONCAT('SELECT x.dt, ', #sql, ' from prices x
group by x.dt');
PREPARE stmt FROM #sql;
EXECUTE stmt;
SQL Fiddle Demo
try it
select a.dt,a.A,CASE WHEN ticker='B' THEN open END AS 'B' from (SELECT dt,CASE WHEN ticker='A' THEN open END AS 'A' FROM test group by dt) a inner join test using(dt) where CASE WHEN ticker='B' THEN open END is not null;
result
+------+-------------------+------+
| dt | A | B |
+------+-------------------+------+
| 1 | 1 | 3 |
| 2 | 1.100000023841858 | 2.5 |
+------+-------------------+------+
Try this:
SELECT GROUP_CONCAT(CONCAT(" MAX(IF(ticker = '", ticker, "', open, NULL)) AS ", ticker)) INTO #sql
FROM prices;
SET #sql = CONCAT('SELECT dt, ', #sql, ' FROM prices GROUP BY dt');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Check this SQL FIDDLE DEMO
OUTPUT
| DT | A | B |
------------------
| 1 | 1 | 3 |
| 2 | 1.1 | 2.5 |