If I have a MySql table with values
col1
=====
1
1
1
5
5
5
5
7
7
I want to get all distinct values of col1 (i.e. 1,5,) and get output with one SELECT statement as follows:
1~1
5~5
7~7
How can I do this?
Here's the query:
Use separator ~ in GROUP_CONCAT function.
Query #1 use case scenario: If you want to separate the col1 values by tide (~) only if the corresponding value has identical values across the table.
Query #1:
SELECT
GROUP_CONCAT(col1 SEPARATOR '~') output
FROM scotttable
GROUP BY col1;
SQL FIDDLE DEMO
Note: It will work for any number of identical values.
Query #2 use case scenario: Only if you want the distinct col1 values no matter if they have corresponding identical value across the table exists or not.
Query #2:
SELECT
CONCAT(col1,'~',col1) output
FROM scotttable
GROUP BY col1;
FIDDLE OF THIS QUERY
Here is an option using a subquery:
SELECT CONCAT(t.value, '~', t.value)
FROM
(
SELECT DISTINCT col1 AS value
FROM yourTable
) t
Follow the link below for a running demo:
SQLFiddle
Related
In my database, I have a table called 'results' with four columns (name,device,passed,failed). Suppose if there are 4 rows in the table as below.
name device passed failed
test1 device_1 2 1
test1 device_2 3 0
test2 device_1 1 2
test2 device_2 2 1
I want the below result:
[(test1,device_1,2,1),(test1,device_2,3,0)]
[(test2,device_1,1,2),(test1,device_2,2,1)]
Is it possible to get that result with only one query to DB?
currently I am querying database twice, first getting a list of distinct names and then getting rows with that name. Below is the pseudo code.
test_names = SELECT DISTINCT name FROM results
for test_name in test_names:
rows = SELECT * FROM results WHERE name=test_name
then I am processing rows to get the object structure that I wanted.
You need concatenation functions like CONCAT_WS() and CONCAT to concatenate the columns of each row and then aggregation with GROUP_CONCAT() for each name:
SELECT CONCAT('[', GROUP_CONCAT(CONCAT('(', CONCAT_WS(',', name, device, passed, failed), ')')), ']') AS result
FROM results
GROUP BY name
See the demo.
SELECT GROUP_CONCAT('(',name,',',device,',',passed,',',failed,')') FROM results group by name;
What i want to get?
Get id,name,email of the people who have sent me friend_requests.
Two tables i have used on the basis of which i want to get the details
signup -> id,name,email,firmname and a few more columns.
friends_requests ->id,userId,sentRequests,receivedRequests,friends,dates
Please refer to the below two images.
friends requests table
Signup table
What I am trying?
SELECT * FROM signup WHERE signup.id IN
(SELECT sentRequests FROM friends_request WHERE friends_request.userId=46)
This query only gives one record, whereas if i use below query it gives 3 records
SELECT * FROM signup WHERE signup.id IN (47,48,49)
I know why second query is giving three records because of the IN clause and three id's
But this query will also give the same result which is 47,48,49
SELECT sentRequests FROM friends_request WHERE friends_request.userId=46
But why isn't the first query giving three records?
When both the values are same? Then why isn't the result same?
About table friends_requests. Column sentRequests violates 1NF.
if I am right, IN operator gets your information as full string, not as separate ID information.
SELECT *
FROM signup
WHERE signup.id IN ('47,48,49')
what is operator thinks IN ('47,48,49')
what You think IN (47,48,49)
You have to split column value '47,48,49' into returning rows so operator could understand, if you want to use IN operator...
For it to work like you coded it,
SELECT sentRequests FROM friends_request WHERE friends_request.userId=46
would have to give 3 rows with 47,48,49.
Because sentRequests is a string it gives one row with 47,48,49
If you want the 3 values go with:
select * from #signup a where exists (select 1 from friends_request b where ','+sentRequests+',' like ',%'+cast(id as varchar(5))+',%')
try this...
SELECT * FROM signup WHERE id IN (
SELECT
DISTINCT cast(SUBSTRING_INDEX(SUBSTRING_INDEX(sentRequests, ',', n.digit+1), ',', -1) AS signed) sentRequests
FROM friends_request INNER JOIN (
SELECT
0 digit
UNION ALL
SELECT 1
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
) n ON LENGTH(REPLACE(sentRequests, ',' , '')) <= LENGTH(sentRequests)-n.digit
WHERE userId = 46
);
I am looking for a way to run a simple SELECT statment. I have a table which has two columns: id and email.
I want to run a SELECT statment that won't return duplicate values. For example, take the following data:
1 example#hotmail.com
2 example12#hotmail.com
3 example#hotmail.com
4 example#hotmail.com
I want it to return only the following:
2 example12#hotmail.com
Use aggregation count(*) and check the result of aggregate function using having clause to filter out those records which are not duplicated
select *
from demo
group by email
having count(*) = 1
Demo
select id,email from table group by email having count(*) =1;
Let assume Following simple table
Col1
======
one
two
Let assume Following simple query
Select count(*) from TABLE_A where Col1 in ('one','two','three','four')
In above query it will produce following result
2
Now I want to find out what are the values in IN- condition which is not available in table_A.
How to find out that values which are not available in table?
like below result
three
four
Above queries only example. In my real time query in have 1000 values in IN-Condition.
Working Database : DB2
This is the one of the work around to achieve your expectation.
Instead of hard-coding the values in IN condition, you can move those values in to a table. If it done simply using LEFT JOIN with NULL check you can get the not matching values.
SELECT MR.Col1
FROM MatchingRecords MR -- here MatchingRecords table contains the IN condition values
LEFT JOIN Table_A TA ON TA.Col1 = MR.Col1
WHERE TA.Col1 IS NULL;
Working DEMO
If the values are to be listed in the statement string rather than stored in a table, then perhaps a revision to the syntax being used for that list of values currently being composed [apparently, from some other input than a TABLE] for the IN predicate can be effected? The following revised syntax for a list of values could be used both for the original aggregate query [shown immediately below as the first of two queries], and for the query for which the how-to-code is being asked [the second of the two queries below]:
Select count(*)
from TABLE_A
where Col1 in ( values('one'),('two'),('three'),('four') )
; -- report from above query follows:
COUNT ( * )
2
[Bgn-Edit 05-Aug-2016: adding this text and example just below]Apparently at least one DB2 variant balks at unnamed columns for the derived table, so the query just below names the column; I chose COL1, so as to match the name from the actual TABLE, but that should not be necessary. The (col1) is added to the original query that remains from the original pre-edit version; that version remains after this edit\insertion and is missing the (col1) added here:
select *
from ( values('one'),('two'),('three'),('four') ) as x (col1)
except ( select * from table_a )
; -- report from above query follows:
COL1
three
four
The following is the original query given, for which the comment below suggests a failure for an unnamed column when run on some unstated DB2 variant; I should have noted that this SQL query functions without error, on DB2 for i 7.1
[End-Edit 05-Aug-2016]
select *
from ( values('one'),('two'),('three'),('four') ) as x
except ( select * from table_a )
; -- report from above query follows:
VALUES
three
four
My query is like this
select 5 from mytable_name;
Then the output is like column name 5 and the value is 5 printing as many max number of rows exists in that table.
Can anybody tell the reason why this query is working like this?
Can anybody tell the reason why this query is working like this?
You are selecting a string literal value '5' for each row in your table:
select 5 from mytable_name;
And this works fine. Because in the SELECT statement you can select:
Column reference,
Literal value like in your case.
Function.
value expression.
Select expression.
As defined by the standard SQL1:
Update:
However, If you have a column with a name is a number like in your case, you have to escape it in order to select the values in it like so:
SELECT `143` FROM Table1;
This will select all the rows in the column 143.
But, this:
SELECT 143 FROM Table1;
Will select the string literal 143 for each row found in the table.
Note that: If possible, try not to name these columns this way, it is recommended and a best practice, not to do this.
SQL Fiddle Demo
Update 2:
Note that, if you select 143 or '143', or even "143" this will select the literal value 143 not the column date. The following are the same:
SELECT 143 FROM Table1;
SELECT '143' FROM Table1;
SELECT "143" FROM Table1;
All these SELECTs won't select the data in the column, They will select the literal value 143 not the column data. See this demo:
Demo
You have to escape the column name with the two:
``
Like this:
SELECT `143` FROM table1;
Not:
SELECT '143' FROM table1'
Like what I did here:
The right Demo
1Image From: SQL Queries for Mere Mortals
from mytable
will select all rows from your table if there is no where condition that shrinks that result. and
select 5
will select the constant number 5 for every record. If you use a column name in the select part then that value will be selected for every record.
The DB engine will name the result 5 because it automatically generates a column name and 5 is the logical name for that.
You want 'SELECT * FROM mytable_name LIMIT 0,5' perhaps?
Since you don't have anything in your where clause, it is selecting all the rows from your table. The fact that you don't select any of the columns is irrelevant - you'll still get a result for each row in the table.
With the command select 5 ... you are viewing a fixed value. Same thing you run the following command: select "test", you will be displaying a fixed string.
Using ... from mytable_name you're looking for all record of this table.
With this we can conclude that for each record in the table mytable_name shows you the fixed value "5".