Simple MySQL Query - Change table format around - mysql

I'm fairly sure this is a fairly easy answer but the answer is completely slipping my mind.
I have a database table that is currently formatted like:
event_id | elem_id | value
1 1 Value 1
1 2 Value 2
2 1 Value 3
2 2 Value 4
Both event_id and elem_id are undetermined numbers and have infinite possibilities.
How would I query it for example based on event_id 1 to get the data to be formatted as such:
event_id | 1 | 2
1 Value 1 Value 2
Knowing that elem_id is a number >= n so potentially there could be 50 elem_id yet I still need the data in that format.
Like I said I can't for the life of me figure out the query to assemble it that way. Any help would be GREATLY appreciated.

Try following:
SELECT
`event_id`,
(SELECT t2.`value` FROM table t2 WHERE t2.`event_id` = t1.`event_id` AND t2.`elem_id` = 1),
(SELECT t3.`value` FROM table t3 WHERE t3.`event_id` = t1.`event_id` AND t3.`elem_id` = 2)
FROM `table` t1 GROUP BY `event_id`;
Also you can use different way, and get elem_ids and values in comma-separated format in two cells
SELECT `event_id`, GROUP_CONCAT(`elem_id`), GROUP_CONCAT(`value`) FROM `table` GROUP BY `event_id`;
and you can change separator with following syntax: GROUP_CONCAT(field SEPARATOR '::')

Related

Show records where a value exist in all instances of a field by group

I am trying to figure out a way to show all records in table where a specific field does not contain certain values - table layout is:
id
tenant_id
request_action
request_id
request_status
hash
Each request_id could have multiple actions so it could look like:
1 1 email 1234 1 ffffd9b00cf893297ab737243c2b921c
2 1 email 1234 0 ffffd9b00cf893297ab737243c2b921c
3 1 email 1234 0 ffffd9b00cf893297ab737243c2b921c
4 1 email 1235 1 a50ee458c9878190c24cdf218c4ac904
5 1 email 1235 1 a50ee458c9878190c24cdf218c4ac904
6 1 email 1235 1 a50ee458c9878190c24cdf218c4ac904
7 1 email 1236 1 58c2869bc4cc38acc03038c7bef14023
8 1 email 1236 2 58c2869bc4cc38acc03038c7bef14023
9 1 email 1236 2 58c2869bc4cc38acc03038c7bef14023
Request_id can either be 0 (pending), 1 (sent) or 2 (failed) - I want to find all hashes where all the request_status within that hash are set to 1.
In the above two examples a50ee458c9878190c24cdf218c4ac904 should return as a match as all the request_status are 1 but ffffd9b00cf893297ab737243c2b921c should not as, whilst it contains a 1, it also contains some 0's and 58c2869bc4cc38acc03038c7bef14023 should not as, again whilst it contains a 1, it also contains some 2's
I tried:
SELECT
*
from
table
where request_action='email' and request_status!=0 and request_status!=2
group by hash
However, this doesn't give me the result I need - how can I return the hashes only where request_status is set to 1 for all the instances of that hash?
Not sure why you would need a group by here. You'd want to do a group by if you were going to concat data using GROUP_CONCAT, or other aggregate functions (sum, max, etc)
Also, instead of doing multiple negative conditions in your where clause (request_status !=0 and request_status !=2), why not just get the status you want?
SELECT * FROM test WHERE request_action = 'email' AND request_status = 1
Update Based on Your Comment
If you don't want to return any hashes that have the status of 0, or 2. You can do this:
SELECT
*
FROM
test t
WHERE
request_action = 'email' AND request_status = 1
AND HASH NOT IN (SELECT HASH FROM test WHERE request_status IN (0, 2))
Just make sure you have an index on hash, otherwise this is going to be really slow.
Create table temp select hash from your_table where
request_status=1 group by hash
Alter table temp add index(hash)
Delete from temp where hash IN (select hash from temp
where request_status!=1 group by hash)
Select * from your_table where hash IN(select hash from
temp)

How to define a custom ORDER BY in MySQL query

I need output in following order(firstly, group by last 3 letters and then arrange in order based on the first 3 digits)
ColumnA
001_eng
004_eng
002_chn
003_usa
But order by ColumnA gives me
ColumnA
001_eng
002_chn
003_usa
004_eng
This is just sample data. I have hundreds of entries in this format and the values keep changing everyday. So, specifying all the entries inside the field is not a feasible option.
I'm not sure of how to use FIELD() in my case.
You can use FIELD:
select *
from tablename
order by
FIELD(ColumnA, '001_eng', '004_eng', '002_chn', '003_usa')
(please be careful if ColumnA is not in the list the field function will return 0 and the rows will be put on top)
or you can use CASE WHEN:
select *
from tablename
order by
case
when ColumnA='001_eng' then 1
when ColumnA='004_eng' then 2
when ColumnA='002_chn' then 3
when ColumnA='003_usa' then 4
else 5
end
or you can use a different languages table where you specify the order:
id | name | sortorder
1 | 001_eng | 1
2 | 002_chn | 3
3 | 003_usa | 4
4 | 004_eng | 2
then you can use a join
select t.*
from
tablename t inner join languages l
on t.lang_id = l.id
order by
l.sortorder
(with proper indexes this would be the better solution with optimal performances)
You can use SUBSTRING_INDEX in case all ColumnA values are formatted like in the sample data:
SELECT *
FROM mytable
ORDER BY FIELD(SUBSTRING_INDEX(ColumnA, '_', -1), 'eng', 'chn', 'usa'),
SUBSTRING_INDEX(ColumnA, '_', 1)
Demo here
you can use substring() and get order by
SELECT *
FROM table_name
ORDER BY SUBSTRING(ColumnA, -7, 3);

count comma-separated values from a column - sql

I want count the length of a comma separated column
I have use these
(LENGTH(Col2) - LENGTH(REPLACE(Col2,",","")) + 1)
in my select query.
Demo:
id | mycolumn
1 2,5,8,60
2 4,5,1
3 5,Null,Null
query result for first two row is coming correctly.for 1 = 4 ,2 = 3 but for 3rd row it is calculating null value also.
Here is what I believe the actual state of your data is:
id | mycolumn
1 2,5,8,60
2 4,5,1
3 NULL
In other words, the entire value for mycolumn in your third record is NULL, likely from doing an operation involving a NULL value. If you actually had the text NULL your current query should still work.
The way to get around this would be to use COALESCE(val, "") when handling the NULL values in your strings.
Crude way of doing it is to replace the occurances of ',Null' with nothing first:-
SELECT a.id, (LENGTH(REPLACE(mycolumn, ',Null', '')) - LENGTH(REPLACE(REPLACE(mycolumn, ',Null', ''),",","")) + 1)
FROM some_table a
If the values refer to the id of rows in another table then you can join against that table using FIND_IN_SET and then count the matches (assuming that the string 'Null' is not an id on that other table)
SELECT a.id, COUNT(b.id)
FROM some_table a
INNER JOIN id_list_table b
ON FIND_IN_SET(b.id, a.mycolumn)
GROUP BY a.id

SQL Query Help - Grouping By Sequences of Digits

I have a table, which includes the following columns and data:
id dtime instance data dtype
1 2012-10-22 10000 d 1
2 2012-10-22 10000 d 1
..
7 2012-10-22 10004 d 1
..
15 2012-10-22 10000 # 1
16 2012-10-22 10004 d 1
17 2012-10-22 10000 d 1
I want to group sequences of 'd's in the data column, with the '#' at the end of the sequence.
This could have been done by grouping via the instance column, which is an individual stream of data, however there can be multiple sequences within the stream.
I also want to end a sequence if there are no data columns in the same instance for, say, 3 seconds after the last data of that instance and no '#'s have been found within that interval.
I have managed to do exactly this using cursors and while loops, which worked reasonably well for tables with 1000s of rows, however this query will be used on far more rows eventually, and these two methods would take around a minute with a dataset of just 3-5000 rows.
Reading on this website and others, it seems that set-based logic may be the way to go, however I can think of no way to do what I need without some kind of loop on each row that compares it to every other to build the 'sequences'.
If anyone could help, or point me in the direction of something that could, it would be greatly appreciated. :)
I would ideally like the data to be output in the following format:
datacount instance lastdata dtime
20 10000 # 2012-10-22
19 10000 d 2012-10-22
22 10004 # 2012-10-22
20 10022 # 2012-10-22
Where (datacount) is a count of the number of rows in a 'sequence' (which is the data leading up to a '#' or 3 second delay), (instance) is the instance ID from the original table, (lastdata) is the last data value in the sequence, (dtime) is the datetime value of the last data value.
Let me show you how to do this for the final '#'. The time difference follows a similar idea. The key idea is to get the next '#' after the current row. For this you need a correlated subquery. After that, you can do a group by:
select groupid, count(*) as NumInSeq, max(dtime) as LastDateTime
from (select t.*,
(select min(t2.id) from t t2 where t2.id > t.id and t2.data = '#'
) as groupid
from t
) t
group by groupid
Handling the time sequence is a bit more complicated. It is something like this:
select groupid, count(*) as NumInSeq, max(dtime) as LastDateTime,
(case when sum(case when data = '#' then 1 else 0 end) > 0 then '#' else 'd' end) as FinalData
from (select t.*,
(select min(t2.id)
from t t2
where t2.id > t.id and
(t2.data = '#' or UNIX_TIMESTAMP(t2.dtime) - UNIX_TIMESTAMP(t.dtime) < 3
) as groupid
from t
) t
group by groupid

MySQL How To Use Main Select Value As Subquery Argument?

I am trying to construct a query that is a bit more complicated than anything I've done in my limited experience with databases.
TABLE:
id - data - type - data3
1 - hello - 1 - 1
2 - goodbye - 1 - 1
3 - goodbye - 1 - 2
4 - goodbye - 2 - 1
5 - hello - 2 - 1
The goal is to do 4 things:
GROUP the results by "data", but only return one result/row of each
data type.
COUNT the total number of each "data GROUP and return this number.
Do this for both "type"=1 and "type"=2, though I only need each
"data" GROUP item once.
the ability to sort results based on each SELECT item.
So the final result returned should be (sorry to be confusing!):
data, COUNT(data["type"]=1), COUNT(data["type"]=2 AND data["data"] = data)
So, for the sample table above, desired results would be:
loop 1 - hello, 2, 1
loop 2 - goodbye, 3, 1
Then, ideally, I could sort results by any of these.
This is the query I was trying to construct before resorting to posting this, I don't think it's even close to being correct, but it may help illustrate what I'm trying to achieve a bit better:
SELECT
(
SELECT `clicks_network_subid_data`, COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '1'
) AS keywords,
(
SELECT COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '2' AND `clicks_network_subid_data` = keywords.clicks_network_subid_data
) AS offer_clicks
GROUP BY keywords.clicks_network_subid_data
ORDER BY keywords.COUNT(*) DESC
I also need to do a JOIN on another table to grab one more piece of data, but I think I can handle that once I get this part figured out.
You can use an IF-function for this
SELECT `clicks_network_subid_data`,
SUM(IF(clicks_click_type` == '1',1,0)) as keywords,
SUM(IF(clicks_click_type` == '2',1,0)) as offer_clicks,
FROM track_clicks
GROUP BY clicks_network_subid_data
ORDER BY clicks_network_subid_data DESC
You can do this using GROUP BY:
SELECT data, COUNT(*) AS cnt FROM `table` GROUP BY type ORDER BY COUNT(*)
Ordering might become a little slow, as this is a calculated field, but if you don't have a large result set then you are good to go.
First of all your question is bit not clear , However, check this query . what I suspect is that you need count results in columns (single ) instead of rows .
select * , count(type_one) as t1_count , count(type_two) as t2_count from (
select data,if(tmp.type=1,1,0) as type_one, if(tmp.type=2,1,0) as type_two from (
select 1 as id , 'hello' as data , 1 as type , 1 as data3 union
select 2 as id , 'goodbye' as data , 1 as type , 1 as data3 union
select 3 as id , 'goodbye' as data , 1 as type , 2 as data3 union
select 4 as id , 'goodbye' as data , 2 as type , 1 as data3 union
select 5 as id , 'hello' as data , 2 as type , 1 as data3
) tmp
) tmp2
group by tmp2.type_one ;
let me know if this works for you
cheers :)