Related
I tried to search posts, but I only found solutions for SQL Server/Access. I need a solution in MySQL (5.X).
I have a table (called history) with 3 columns: hostid, itemname, itemvalue.
If I do a select (select * from history), it will return
+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
| 1 | A | 10 |
+--------+----------+-----------+
| 1 | B | 3 |
+--------+----------+-----------+
| 2 | A | 9 |
+--------+----------+-----------+
| 2 | C | 40 |
+--------+----------+-----------+
How do I query the database to return something like
+--------+------+-----+-----+
| hostid | A | B | C |
+--------+------+-----+-----+
| 1 | 10 | 3 | 0 |
+--------+------+-----+-----+
| 2 | 9 | 0 | 40 |
+--------+------+-----+-----+
I'm going to add a somewhat longer and more detailed explanation of the steps to take to solve this problem. I apologize if it's too long.
I'll start out with the base you've given and use it to define a couple of terms that I'll use for the rest of this post. This will be the base table:
select * from history;
+--------+----------+-----------+
| hostid | itemname | itemvalue |
+--------+----------+-----------+
| 1 | A | 10 |
| 1 | B | 3 |
| 2 | A | 9 |
| 2 | C | 40 |
+--------+----------+-----------+
This will be our goal, the pretty pivot table:
select * from history_itemvalue_pivot;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | 0 |
| 2 | 9 | 0 | 40 |
+--------+------+------+------+
Values in the history.hostid column will become y-values in the pivot table. Values in the history.itemname column will become x-values (for obvious reasons).
When I have to solve the problem of creating a pivot table, I tackle it using a three-step process (with an optional fourth step):
select the columns of interest, i.e. y-values and x-values
extend the base table with extra columns -- one for each x-value
group and aggregate the extended table -- one group for each y-value
(optional) prettify the aggregated table
Let's apply these steps to your problem and see what we get:
Step 1: select columns of interest. In the desired result, hostid provides the y-values and itemname provides the x-values.
Step 2: extend the base table with extra columns. We typically need one column per x-value. Recall that our x-value column is itemname:
create view history_extended as (
select
history.*,
case when itemname = "A" then itemvalue end as A,
case when itemname = "B" then itemvalue end as B,
case when itemname = "C" then itemvalue end as C
from history
);
select * from history_extended;
+--------+----------+-----------+------+------+------+
| hostid | itemname | itemvalue | A | B | C |
+--------+----------+-----------+------+------+------+
| 1 | A | 10 | 10 | NULL | NULL |
| 1 | B | 3 | NULL | 3 | NULL |
| 2 | A | 9 | 9 | NULL | NULL |
| 2 | C | 40 | NULL | NULL | 40 |
+--------+----------+-----------+------+------+------+
Note that we didn't change the number of rows -- we just added extra columns. Also note the pattern of NULLs -- a row with itemname = "A" has a non-null value for new column A, and null values for the other new columns.
Step 3: group and aggregate the extended table. We need to group by hostid, since it provides the y-values:
create view history_itemvalue_pivot as (
select
hostid,
sum(A) as A,
sum(B) as B,
sum(C) as C
from history_extended
group by hostid
);
select * from history_itemvalue_pivot;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | NULL |
| 2 | 9 | NULL | 40 |
+--------+------+------+------+
(Note that we now have one row per y-value.) Okay, we're almost there! We just need to get rid of those ugly NULLs.
Step 4: prettify. We're just going to replace any null values with zeroes so the result set is nicer to look at:
create view history_itemvalue_pivot_pretty as (
select
hostid,
coalesce(A, 0) as A,
coalesce(B, 0) as B,
coalesce(C, 0) as C
from history_itemvalue_pivot
);
select * from history_itemvalue_pivot_pretty;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | 0 |
| 2 | 9 | 0 | 40 |
+--------+------+------+------+
And we're done -- we've built a nice, pretty pivot table using MySQL.
Considerations when applying this procedure:
what value to use in the extra columns. I used itemvalue in this example
what "neutral" value to use in the extra columns. I used NULL, but it could also be 0 or "", depending on your exact situation
what aggregate function to use when grouping. I used sum, but count and max are also often used (max is often used when building one-row "objects" that had been spread across many rows)
using multiple columns for y-values. This solution isn't limited to using a single column for the y-values -- just plug the extra columns into the group by clause (and don't forget to select them)
Known limitations:
this solution doesn't allow n columns in the pivot table -- each pivot column needs to be manually added when extending the base table. So for 5 or 10 x-values, this solution is nice. For 100, not so nice. There are some solutions with stored procedures generating a query, but they're ugly and difficult to get right. I currently don't know of a good way to solve this problem when the pivot table needs to have lots of columns.
SELECT
hostid,
sum( if( itemname = 'A', itemvalue, 0 ) ) AS A,
sum( if( itemname = 'B', itemvalue, 0 ) ) AS B,
sum( if( itemname = 'C', itemvalue, 0 ) ) AS C
FROM
bob
GROUP BY
hostid;
Another option,especially useful if you have many items you need to pivot is to let mysql build the query for you:
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'ifnull(SUM(case when itemname = ''',
itemname,
''' then itemvalue end),0) AS `',
itemname, '`'
)
) INTO #sql
FROM
history;
SET #sql = CONCAT('SELECT hostid, ', #sql, '
FROM history
GROUP BY hostid');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
FIDDLE
Added some extra values to see it working
GROUP_CONCAT has a default value of 1000 so if you have a really big query change this parameter before running it
SET SESSION group_concat_max_len = 1000000;
Test:
DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);
INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);
hostid A B C D
1 10 3 0 0
2 9 0 40 5
3 14 67 0 8
Taking advantage of Matt Fenwick's idea that helped me to solve the problem (a lot of thanks), let's reduce it to only one query:
select
history.*,
coalesce(sum(case when itemname = "A" then itemvalue end), 0) as A,
coalesce(sum(case when itemname = "B" then itemvalue end), 0) as B,
coalesce(sum(case when itemname = "C" then itemvalue end), 0) as C
from history
group by hostid
I edit Agung Sagita's answer from subquery to join.
I'm not sure about how much difference between this 2 way, but just for another reference.
SELECT hostid, T2.VALUE AS A, T3.VALUE AS B, T4.VALUE AS C
FROM TableTest AS T1
LEFT JOIN TableTest T2 ON T2.hostid=T1.hostid AND T2.ITEMNAME='A'
LEFT JOIN TableTest T3 ON T3.hostid=T1.hostid AND T3.ITEMNAME='B'
LEFT JOIN TableTest T4 ON T4.hostid=T1.hostid AND T4.ITEMNAME='C'
use subquery
SELECT hostid,
(SELECT VALUE FROM TableTest WHERE ITEMNAME='A' AND hostid = t1.hostid) AS A,
(SELECT VALUE FROM TableTest WHERE ITEMNAME='B' AND hostid = t1.hostid) AS B,
(SELECT VALUE FROM TableTest WHERE ITEMNAME='C' AND hostid = t1.hostid) AS C
FROM TableTest AS T1
GROUP BY hostid
but it will be a problem if sub query resulting more than a row, use further aggregate function in the subquery
If you could use MariaDB there is a very very easy solution.
Since MariaDB-10.02 there has been added a new storage engine called CONNECT that can help us to convert the results of another query or table into a pivot table, just like what you want:
You can have a look at the docs.
First of all install the connect storage engine.
Now the pivot column of our table is itemname and the data for each item is located in itemvalue column, so we can have the result pivot table using this query:
create table pivot_table
engine=connect table_type=pivot tabname=history
option_list='PivotCol=itemname,FncCol=itemvalue';
Now we can select what we want from the pivot_table:
select * from pivot_table
More details here
My solution :
select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
from history
) h group by hostid
It produces the expected results in the submitted case.
I make that into Group By hostId then it will show only first row with values,
like:
A B C
1 10
2 3
I figure out one way to make my reports converting rows to columns almost dynamic using simple querys. You can see and test it online here.
The number of columns of query is fixed but the values are dynamic and based on values of rows. You can build it So, I use one query to build the table header and another one to see the values:
SELECT distinct concat('<th>',itemname,'</th>') as column_name_table_header FROM history order by 1;
SELECT
hostid
,(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue else '' end) as col1
,(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue else '' end) as col2
,(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue else '' end) as col3
,(case when itemname = (select distinct itemname from history a order by 1 limit 3,1) then itemvalue else '' end) as col4
FROM history order by 1;
You can summarize it, too:
SELECT
hostid
,sum(case when itemname = (select distinct itemname from history a order by 1 limit 0,1) then itemvalue end) as A
,sum(case when itemname = (select distinct itemname from history a order by 1 limit 1,1) then itemvalue end) as B
,sum(case when itemname = (select distinct itemname from history a order by 1 limit 2,1) then itemvalue end) as C
FROM history group by hostid order by 1;
+--------+------+------+------+
| hostid | A | B | C |
+--------+------+------+------+
| 1 | 10 | 3 | NULL |
| 2 | 9 | NULL | 40 |
+--------+------+------+------+
Results of RexTester:
http://rextester.com/ZSWKS28923
For one real example of use, this report bellow show in columns the hours of departures arrivals of boat/bus with a visual schedule. You will see one additional column not used at the last col without confuse the visualization:
** ticketing system to of sell ticket online and presential
This isn't the exact answer you are looking for but it was a solution that i needed on my project and hope this helps someone. This will list 1 to n row items separated by commas. Group_Concat makes this possible in MySQL.
select
cemetery.cemetery_id as "Cemetery_ID",
GROUP_CONCAT(distinct(names.name)) as "Cemetery_Name",
cemetery.latitude as Latitude,
cemetery.longitude as Longitude,
c.Contact_Info,
d.Direction_Type,
d.Directions
from cemetery
left join cemetery_names on cemetery.cemetery_id = cemetery_names.cemetery_id
left join names on cemetery_names.name_id = names.name_id
left join cemetery_contact on cemetery.cemetery_id = cemetery_contact.cemetery_id
left join
(
select
cemetery_contact.cemetery_id as cID,
group_concat(contacts.name, char(32), phone.number) as Contact_Info
from cemetery_contact
left join contacts on cemetery_contact.contact_id = contacts.contact_id
left join phone on cemetery_contact.contact_id = phone.contact_id
group by cID
)
as c on c.cID = cemetery.cemetery_id
left join
(
select
cemetery_id as dID,
group_concat(direction_type.direction_type) as Direction_Type,
group_concat(directions.value , char(13), char(9)) as Directions
from directions
left join direction_type on directions.type = direction_type.direction_type_id
group by dID
)
as d on d.dID = cemetery.cemetery_id
group by Cemetery_ID
This cemetery has two common names so the names are listed in different rows connected by a single id but two name ids and the query produces something like this
CemeteryID Cemetery_Name Latitude
1 Appleton,Sulpher Springs 35.4276242832293
You can use a couple of LEFT JOINs. Kindly use this code
SELECT t.hostid,
COALESCE(t1.itemvalue, 0) A,
COALESCE(t2.itemvalue, 0) B,
COALESCE(t3.itemvalue, 0) C
FROM history t
LEFT JOIN history t1
ON t1.hostid = t.hostid
AND t1.itemname = 'A'
LEFT JOIN history t2
ON t2.hostid = t.hostid
AND t2.itemname = 'B'
LEFT JOIN history t3
ON t3.hostid = t.hostid
AND t3.itemname = 'C'
GROUP BY t.hostid
I'm sorry to say this and maybe I'm not solving your problem exactly but PostgreSQL is 10 years older than MySQL and is extremely advanced compared to MySQL and there's many ways to achieve this easily. Install PostgreSQL and execute this query
CREATE EXTENSION tablefunc;
then voila! And here's extensive documentation: PostgreSQL: Documentation: 9.1: tablefunc or this query
CREATE EXTENSION hstore;
then again voila! PostgreSQL: Documentation: 9.0: hstore
I have a result like this:
I need to update "flag" column as duplicate when any one word from the row matches with second row within group of "mfgid" column.
--test dataset
declare #table as table
(id int,
mfgid int,
[desc] varchar(100))
insert into #table
values (1,111,'abc xyz pqr'),
(2,111,'abc tyu fgh'),
(3,222,'abc pqr'),
(4,222,'lmn stu'),
(5,333,'pqr spd hki abc'),
(6,333,'lmn jsk pqr klo')
How can I do this?
Here is a possible solution
WITH K AS
(
SELECT mfgid,
value,
count(*) over ( partition by mfgid, value order by mfgid) Dups
FROM #Table cross apply STRING_SPLIT([desc], ' ')
)
SELECT T.*,
IIF(
EXISTS(SELECT 1 FROM K WHERE K.mfgid = T.mfgid AND K.Dups > 1),
'Duplicte',
''
) Flag
FROM #Table T;
Results:
+----+-------+-----------------+----------+
| id | mfgid | desc | Flag |
+----+-------+-----------------+----------+
| 1 | 111 | abc xyz pqr | Duplicte |
| 2 | 111 | abc tyu fgh | Duplicte |
| 3 | 222 | abc pqr | |
| 4 | 222 | lmn stu | |
| 5 | 333 | pqr spd hki abc | Duplicte |
| 6 | 333 | lmn jsk pqr klo | Duplicte |
+----+-------+-----------------+----------+
Demo
two possible solutions below:
--test dataset
declare #table as table
(id int,
mfgid int,
[desc] varchar(100))
insert into #table
values (1,111,'abc xyz pqr'),
(2,111,'abc tyu fgh'),
(3,222,'abc pqr'),
(4,222,'lmn stu'),
(5,333,'pqr spd hki abc'),
(6,333,'lmn jsk pqr klo')
Solution 1:
If you have only 4 words in string (based on your screenshot)
;with cte2 as
(select *
from (select id,
mfgid,
parsename(replace(s.[desc],' ','.'),1) as [a1],
parsename(replace(s.[desc],' ','.'),2) as [a2],
parsename(replace(s.[desc],' ','.'),3) as [a3],
parsename(replace(s.[desc],' ','.'),4) as [a4]
from #table as s) as a
unpivot (testval FOR val IN (a1, a2, a3, a4)) unpvt
)
select m.id, m.mfgid, m.[desc], t.flag
from #table as m
outer apply
(select top (1) 'duplicate' as flag
from cte2 as a
join cte2 as b
on a.mfgid = b.mfgid
and a.id != b.id
and a.testval = b.testval
and m.mfgid = a.mfgid) as t
test is here
Solution 2:
If you have more that 4 words in string
;with cte as
( select t.*, s.[value]
from #table as t
cross apply
(select ltrim(rtrim(split.a.value('.','varchar(100)'))) as [value]
from (select cast('<M>'+replace([desc],' ','</M><M>')+'</M>' as xml) as data) as a
cross apply data.nodes ('/M') as split(a)
) as s
)
select m.id, m.mfgid, m.[desc], t.flag
from #table as m
outer apply
(select top (1) 'duplicate' as flag
from cte as a
join cte as b
on a.mfgid = b.mfgid
and a.id != b.id
and a.Value = b.Value
and m.mfgid = a.mfgid) as t
test is here
This assumes the OP is using SQL Server 2016+, as they haven't let us know the version:
WITH Split AS(
SELECT T.id,
T.mfgid,
T.[desc],
SS.[value]
FROM #table T
CROSS APPLY STRING_SPLIT([desc],' ') SS)
SELECT S.id,
S.mfgid,
S.[desc],
CASE MAX(Dups) WHEN 0 THEN NULL ELSE 'Duplicate' END AS Flag
FROM Split S
CROSS APPLY (SELECT COUNT(*) AS [Dups]
FROM Split ca
WHERE ca.mfgid = S.mfgid
AND ca.[value] = S.[value]
AND ca.id != S.id) C
GROUP BY S.id,
S.mfgid,
S.[desc];
I have two rows with the same id but different values. I want a query to get the second value and display it in the first row.
There are only two rows for each productId and 2 different values.
I've tried looking for this for the solution everywhere.
What I have, example:
+-----+-------+
| ID | Value |
+-----+-------+
| 123 | 1 |
| 123 | 2 |
+-----+-------+
What I want
+------+-------+---------+
| ID | Value | Value 1 |
+------+-------+---------+
| 123 | 1 | 2 |
+------+-------+---------+
Not sure whether order matters to you. Here is one way:
SELECT MIN(Value), MAX(Value), ID
FROM Table
GROUP BY ID;
This is a self-join:
SELECT a.ID, a.Value, b.Value
FROM table a
JOIN table b on a.ID = b.ID
and a.Value <> b.Value
You can use a LEFT JOIN instead if there are IDs that only have one value and would be lost by the above JOIN
May be you may try this
DECLARE #T TABLE
(
Id INT,
Val INT
)
INSERT INTO #T
VALUES(123,1),(123,2),
(456,1),(789,1),(789,2)
;WITH CTE
AS
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Val),
*
FROM #T
)
SELECT
*
FROM CTE
PIVOT
(
MAX(Val)
FOR
RN IN
(
[1],[2]--Add More Numbers here if there are more values
)
)Q
Let's say I have a table
OrgData
OrgDataid columvalues
1 1,2,3,4,5
2 6,7,8,9
3 16,17,18,19
Another table holds selected values
selectedData
rowid sid orgid values
1 1 1 1,2
2 1 2 6,7,8,9
3 2 1 1,2,3,4,5
Where sid is the id of OrgData
I want output like
for sid 1;
outputData
OrgData columvalues
1 partial selected
2 Full selected
3 Nothing selected
I want some straightway query, while I am trying to do it with splitting every comma separated to rows and looping for each one.
Thanks
You might try this:
--mock-up-tables with your data
DECLARE #OrgData TABLE(OrgDataid INT,columvalues VARCHAR(100));
INSERT INTO #OrgData VALUES
(1,'1,2,3,4,5')
,(2,'6,7,8,9')
,(3,'16,17,18,19');
DECLARE #selectedData TABLE(rowid INT,[sid] INT,orgid INT,[values] VARCHAR(100));
INSERT INTO #selectedData VALUES
(1,1,1,'1,2')
,(2,1,2,'6,7,8,9')
,(3,2,1,'1,2,3,4,5');
--First CTE to split OrgData
WITH OrgDataSplitted AS
(
SELECT od.*
,LEN(od.columvalues)-LEN(REPLACE(od.columvalues,',',''))+1 AS CountParts
,B.Part.value('.','int') AS PartInt
FROM #OrgData AS od
CROSS APPLY(SELECT CAST('<x>' + REPLACE(columvalues,',','</x><x>') + '</x>' AS XML)) AS A(Casted)
CROSS APPLY A.Casted.nodes('/x') AS B(Part)
)
--Second CTE to split SelectedData
,SelectedSplitted AS
(
SELECT sd.*
,B.Part.value('.','int') AS PartInt
FROM #selectedData AS sd
CROSS APPLY(SELECT CAST('<x>' + REPLACE([values],',','</x><x>') + '</x>' AS XML)) AS A(Casted)
CROSS APPLY A.Casted.nodes('/x') AS B(Part)
)
--The query to join them
SELECT o.OrgDataid,o.CountParts,s.rowid,COUNT(rowid) AS CountIdent
FROM Orgdatasplitted AS o
FULL OUTER JOIN SelectedSplitted AS s ON o.OrgDataID=s.orgid and o.PartInt=s.PartInt
GROUP BY o.OrgDataid,o.CountParts,s.rowid
ORDER BY o.OrgDataid
The result. If CountParts and CountIdent is the same it's full, >0 is partial and 0 is none
+-----------+------------+-------+------------+
| OrgDataid | CountParts | rowid | CountIdent |
+-----------+------------+-------+------------+
| 1 | 5 | 1 | 2 |
+-----------+------------+-------+------------+
| 1 | 5 | 3 | 5 |
+-----------+------------+-------+------------+
| 2 | 4 | 2 | 4 |
+-----------+------------+-------+------------+
| 3 | 4 | NULL | 0 |
+-----------+------------+-------+------------+
Try the below script, may be help you. But I agree with #Gordon Linoff,
Fix you data structure. Storing values in comma-delimited strings is the wrong way.
SELECT OrgDataid
,(CASE WHEN OD.columvalues = SD.[values] THEN 'Full selected'
WHEN SD.rowid IS NULL THEN 'Nothing selected'
ELSE 'partial selected' END) AS columvalues
FROM OrgData AS OD
LEFT OUTER JOIN selectedData AS SD ON OD.columvalues LIKE '%'+SD.[values]+'%'
I need to write a sql query on the table such that the result would have the group by column along with the aggregated column with comma separators.
My table would be in the below format
|`````````|````````|
| ID | Value |
|_________|________|
| 1 | a |
|_________|________|
| 1 | b |
|_________|________|
| 2 | c |
|_________|________|
Expected result should be in the below format
|`````````|````````|
| ID | Value |
|_________|________|
| 1 | a,b |
|_________|________|
| 2 | c |
|_________|________|
You want to use FOR XML PATH construct:
select
ID,
stuff((select ', ' + Value
from YourTable t2 where t1.ID = t2.ID
for xml path('')),
1,2,'') [Values]
from YourTable t1
group by ID
The STUFF function is to get rid of the leading ', '.
You can also see another examples here:
SQL same unit between two tables needs order numbers in 1 cell
SQL and Coldfusion left join tables getting duplicate results as a list in one column
Just for a balanced view, you can also do this with a CTE but its not as good as the cross apply method I don't think. I've coded this of the hoof so apologies if it doesn't work.
WITH CommaDelimitedCTE (RowNumber,ID,[Value],[Values]) AS
(
SELECT 1,MT.ID , MIN(MT.Value), CAST(MIN(MT.Value) AS VARCHAR(8000))
FROM MyTable MT
GROUP BY MT.ID
UNION ALL
SELECT CT.RowNumber + 1, MT.ID, MT.Value, CT.[Values] + ', ' + MT.Value
FROM MyTable MT
INNER JOIN CommaDelimitedCTE CT ON CT.ID = MT.ID
WHERE MT.[Value] > CT.[Value]
)
Select CommaDelimitedCTE.* from CommaDelimitedCTE
INNER JOIN (SELECT MT.ID,MAX(RowNumber) as MaxRowNumber from CommaDelimitedCTE GROUP BY MT.ID) Q on Q.MT.ID = CommaDelimitedCTE.MT.ID
AND Q.MaxRowNumber = CommaDelimitedCTE.RowNumber
In SQL Server 2017 (14.x) and later you can use the STRING_AGG function:
https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver16
SELECT
ID,
STRING_AGG(Value, ',')
FROM TableName
GROUP BY ID
Depending on the data type of Value you might need to convert it:
SELECT
ID,
STRING_AGG(CONVERT(NVARCHAR(max), Value), ',')
FROM TableName
GROUP BY ID