Select similar records from mysql - mysql

I have a database as shown below
ID color number code
102966 red 1 9f6606069f9b999b
102968 red 1 9f6606069f9b999b
102967 red 1 9f0606069f9f9f9f
102969 red 1 9f0606069f9f9f9f
103630 red 1 bbff9f0f8fdc9f7e
101582 red 1 bbff9b0fcf9f99d9
102000 red 1 99fd9f0fab999fff
101603 red 1 bbff9f0d8f9d96df
102016 red 1 bbff9900c09999df
This table has more then 4000 entries.
I got this output by using
Select * from mytable order by code asc
Now I want output as a Id-Id-Id.... where code is similar.
So for given snippet it should come like
102966-102968
102967-102969
So I want like that those records are similar, their code should come like this.
Please help.

I don't really see what your last result row is about, it might be a mistake or I don't understand what you need
I think you are looking for a group_concat
select group_concat(ID ORDER BY ID SEPARATOR '-' ) AS dup
from mytable
GROUP BY code
HAvING count(*) >1
ORDER BY dup
Results:
| dup |
|---------------|
| 102966-102968 |
| 102967-102969 |
A group_concat shows all the values matching the GROUP BY, here the ID values.
The term SEPARATOR is there to specify - as separator between your IDs, because the default separator is ,
If you want all rows, even those for which there are no duplicate code, remove the having clause
SQL Fiddle

the last answer from #Thomas G is correct but if you want to have it in the correct order use:
select CONCAT(MIN(ID),'-',MAX(ID))
from mytable
GROUP BY code
HAvING count(*) >1

Related

How to count the length of column seperated by ',' after using group_concat [duplicate]

This question already has answers here:
How to count items in comma separated list MySQL
(6 answers)
Closed 3 years ago.
I have a table looks like below:
ID path
| 1 YouTube,Newsletter,Social
| 2 YouTube,Newsletter
| 3 YouTube
Now I want to create a column to count the length of the path column. such as below:
ID path count weights
| 1 YouTube,Newsletter,Social 3 0.33
| 2 YouTube,Newsletter 2 0.5
| 3 YouTube 1 1
How do I do this?
I have tried JSON_LENGTH but couldn't get the command working.
PS. essentially I'm trying to replicate a query in PostgreSQL:
' select user_id, channels, 1.0 / array_length(channels, 1) as weights
from (
// ... query for marketing_channels as before)'
I am using MYSQL.
select d.email_entry_id
,d.channels
,JSON_LENGTH(d.channels)
from (
select email_entry_id
,group_concat(attribution_string order by visit_date asc separator ',' ) as channels
from database) d
error message: Error Code: 1370. execute command denied to user 'yb'#'%' for routine 'company.JSON_LENGTH'
Hope the question is clear enough. let me know if i need to clarify anything.
If I followed you correctly, you could simply extend the logic of your existing query (which, by the way, seems to be missing a GROUP BY clause). Instead of querying the aggregated data, it would be simpler to start from the original data, like:
SELECT
email_entry_id,
GROUP_CONCAT(attribution_string ORDER BY visit_date SEPARATOR ',' ) as channels,
COUNT(*) as `count`,
1/COUNT(*) as weight
FROM database
GROUP BY email_entry_id
There is a very common trick to achieve such outcome, demonstrated by following query
SELECT ID, PATH,
(LENGTH(PATH) - LENGTH(REPLACE(PATH, ',', ''))) + 1 COUNT
FROM DATABASE /* OR WHATEVER IS THE TABLE NAME */
The result

How to insert SUM() function that sums rows with similar ID in a code part of witch is unchangeable?

I am trying to write a quarry in a module for Dolibarr ERP. But module hase a part of code that is predefined and can not be changed. And I need to insert a SUM() function in it that will combine rows with similar id. That i know how to do in a regular MySQL:
SELECT fk_product AS prod, SUM(value) AS qty
FROM llx_stock_mouvement
WHERE type_mouvement = 2 AND label LIKE 'SH%'
GROUP BY fk_product
ORDER BY 1 DESC
LIMIT 26
that gives me what I want :
prod qty
1 13
2 10
BUT module has a predefined unchangeable code :
this part is predefined module writes it himself based on values provider in it:
SELECT DISTINCT
c.fk_product AS com,
c.value AS qty
THIS PART I CAN WRITE IN A MODULES GUI:
FROM
llx_stock_mouvement AS c
WHERE
type_mouvement = 2
AND label LIKE 'SH%'
And this part is predefined:
ORDER BY 1 DESC
LIMIT 26
I would appreciate any help and advice on question is there any workaround that can be done to make my desired and result ampere ? As it would using the first code I posted ?
If you can only modify the bit in the middle box then you might need to use a subquery;
--fixed part
SELECT DISTINCT
c.fk_product AS com,
c.value AS qty
--begin your editable part
FROM
(
SELECT fk_product,
SUM(value) AS value
FROM llx_stock_mouvement
WHERE type_mouvement = 2 AND label LIKE 'SH%'
GROUP BY fk_product
) c
--end your editable part
--fixed part
ORDER BY 1
DESC
LIMIT 26

Need help returning duplicates from a join onto a single line with a sum function included

I have two tables t1 and t2. t1 contains some message data i have set up to be searched against t2 which contains a list of keywords all with their own individual score. Now I have been moderately successful with this and have managed to return all rows in t1 that contain any keyword within t2 with this query
SELECT DISTINCT t1.RowID, t1.ChatNo, t1.UserNo,
t1.Chat, t2.Keywords, SUM(t2.KeywordScore) AS Score
FROM t1
LEFT JOIN t2 ON t1.Chat LIKE CONCAT('%', + t2.Keywords , + '%')
WHERE t2.Keywords IS NOT NULL OR t1.ChatNo > 0 AND t1.UserNo > 0
GROUP BY t1.RowID, t2.Keywords
Now my issue is, it returns duplicate results if a chat message has multiple keywords and on each duplicate row it will have picked up a different keyword and that keywords score. Now because of this I believe my query is attempting to sum the rows individually so cannot total them up (correct me if i am wrong).
for example:
RowID ChatNo UserNO Chat Keywords Score
1 1 1 "...ex1 ex2 ex3" ex1 2
1 1 1 "...ex1 ex2 ex3" ex2 4
1 1 1 "...ex1 ex2 ex3" ex3 1
Now what I would like it to do is to return all the keywords found in a message on a single line (or list) and still be able to SUM up the values of the keywords found within the message and display the total, like so:
RowID ChatNo UserNO Chat Keywords Score
1 1 1 "...ex1 ex2 ex3" ex1, ex2, ex3 7
I have done some searching and testing haven't really come across a solution that has worked for me. So if anyone can give me some assistance on how I might proceed and get the query to output the results on a single line with a the score summed up it would be greatly appreciated.
You need to use GROUP_CONCAT()
Also distinct doesn't seem necessary so I deleted it.
Try this:
SELECT t1.RowID, t1.ChatNo, t1.UserNo,
t1.Chat, group_concat(t2.Keywords, ', '), SUM(t2.KeywordScore) AS Score
FROM t1
LEFT JOIN t2 ON t1.Chat LIKE CONCAT('%', + t2.Keywords , + '%')
WHERE t2.Keywords IS NOT NULL OR t1.ChatNo > 0 AND t1.UserNo > 0
GROUP BY t1.RowID, t1.ChatNo, t1.UserNo, t1.Chat

SQL stament groups rows and calculate average

I am stuck with the following issue. I have 1 table that looks like this:
field_number.. Value
````````````````````````````````
1 ......................... 1
2 ..........................1
3 ......................... 2
4 ..........................2
etc.
I want to group different fieldnumbers and have an average for the value column. So the output should be:
field_number................Value
name(1,2)...................... 1.............. ((1+1)/2)
name(3,4)...................... 2.............. ((2+2)/2)
I have checked previous questions but cannot find any question that covers this issue (I might search on the wrong keywords though). So if this has already been covered my appologies, but any help or a point to a previous answer would be appreciated.
** =============UPDATE============= **
I went through your suggestions but did not get it right. So I am trying to be more specific. I almost have the result I want apart from the fact I want to have a fixed value in one of my columns. I have the following query:
Select
Avg(wp_rg_lead_detail.value),
wp_rg_lead_detail.field_number,
From
wp_rg_lead_detail
Where
wp_rg_lead_detail.field_number In (15, 17, 24) A
UNION
Select
Avg(wp_rg_lead_detail.value),
wp_rg_lead_detail.field_number,
From
wp_rg_lead_detail
Where
wp_rg_lead_detail.field_number In (16, 108, 18)
etc.
This gives me a table with two columns
wp_rg_lead_detail.value................field_number
4.3 (average)..............................15 (first value of av calculation)
What I want is to change the field number (15 in this case) in a fixed value (text). What and how should I add this to the query?
SELECT avg(value) FROM table WHERE field_number in (1,2)
SELECT avg(value) FROM table WHERE field_number in (3,4)
If your table is really this simple, you can also get away with:
select distinct
Value,
count(Value) as '#'
from table_name
group by Value
If you acctually want to group by a range, than you can put the logic of the range in your grouping clause (see this fiddle)
select distinct
avg(Value) as average,
floor(Value),
count(Value) as '#'
from table_name
group by floor(Value)
In the fiddle I used grouping on whole integers, but you can make that as complex as you like (see, for instance, this example)
If you are actually also interested in your corresponding fields, use group_concat() like so
select
Value,
group_concat(
distinct field_number
order by Value
) as fields
from table_name tn1
group by Value
order by Value
output:
Value | fields
---------------------------------
1 | 1,2
2 | 3,4
See this fiddle implemented from this blog post
For a generalized answer.
SELECT CONCAT('name','(',GROUP_CONCAT(field_number),')') AS field_number,
AVG(Value) as Value
FROM table_name
group by table_name.`Value`
Hope this helps.

How to return ordered data from multiple records into one record in MySQL?

I have a MySQL database with a table of survey responses with three important fields (renamed for clarity): SURVEY_TAKER_ID, QUESTION_NUMBER, and RESPONSE. Assuming a 3-question survey as an example, it would look something like this:
SURVEY_TAKER_ID | QUESTION_NUMBER | RESPONSE
----------------------------------------
101 1 Apple
102 1 Orange
103 1 Banana
101 2 Morning
102 2 Evening
103 2 Afternoon
101 3 Red
102 3 Blue
103 3 Yellow
I would like to create a SELECT query that outputs each survey taker's ID and responses in order by question number, e.g.:
101,Apple,Morning,Red
102,Orange,Evening,Blue
103,Banana,Afternoon,Yellow
I know that SQL Server has FOR XML, which can make this easier, but my database is in MySQL, and I must admit that I'm not really all that adept at SQL in the first place. Can anyone please give me a sample query that would produce the output above, or point me to a way to do it?
Many thanks to anyone who can help...
...Jay
SURVEY_TAKER_ID with "Question_Number: RESPONSE" style concating:
SQL Fiddle
SELECT SURVEY_TAKER_ID
,GROUP_CONCAT(CONCAT(QUESTION_NUMBER, ': ', RESPONSE) ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
FROM Table1
GROUP BY SURVEY_TAKER_ID
ORDER BY SURVEY_TAKER_ID
.
SURVEY_TAKER_ID with "RESPONSE" alone style concating:
SQL Fiddle
SELECT SURVEY_TAKER_ID
,GROUP_CONCAT(RESPONSE ORDER BY QUESTION_NUMBER SEPARATOR ', ') AS RESPONSES
FROM Table1
GROUP BY SURVEY_TAKER_ID
ORDER BY SURVEY_TAKER_ID
Try this:
SELECT CONCAT(SURVEY_TAKER_ID, ',', RESPONSE)
FROM (SELECT SURVEY_TAKER_ID, GROUP_CONCAT(RESPONSE) RESPONSE
FROM (SELECT * FROM SURVEY ORDER BY SURVEY_TAKER_ID, QUESTION_NUMBER) A
GROUP BY SURVEY_TAKER_ID
) A