SQL: Select key based on missing value [closed] - mysql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have one table created like this
Table:
key value
1 10000
1 10001
2 10001
And I want to select key 2 because it has 10001 but not 10000. Is there a simple way? I tried using joins but I have no idea how to make join select only missing value.

Assuming you're looking for keys that don't have all of the available values, you can do that by comparing the number of DISTINCT values for each key to the number of DISTINCT values in the entire table.
SELECT `key` FROM `table`
GROUP BY `key`
HAVING COUNT(DISTINCT value) < (SELECT COUNT(DISTINCT value) FROM `table`)
Seen in action at SQLFiddle
If there are only a particular set of values you're interested in, you can change this to using hardcoded values.
SELECT `key` FROM `table`
WHERE value IN (10001, 10000)
GROUP BY `key`
HAVING COUNT(DISTINCT value) < 2
For this to generalize to a larger number of values, the number in the HAVING clause needs to match the number of elements in the IN condition.

You can simply do this:
SELECT DISTINCT t1.`key`
FROM tablename t1
WHERE t1.`key` NOT IN(SELECT `key`
FROM tablename
WHERE value = 10000);
SQL Fiddle Demo

I think the easiest way to approach this problem is to put the logic in the having clause. The following counts the number of times each key appears and applies your logic:
select "key"
from t
group by "key"
having sum(value = 10000) = 0 and
sum(value = 10001) > 0;
This is using a MySQL feature where boolean expressions (value = 10000) are treated as integers, with 0 being false and 1 being true. So, sum(value = 10000) counts the number of rows where value is 10000 for each key.

Related

For a particular datetime, find a record with the closest datetime before and after [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Let's have a MySQL database table that contains a DateTime column when. Such a column may carry any DateTime value other than NULL.
How can I create a table that would contain columns when, whenA, and whenB, with all full-minute DateTime values (YYYY-MM-DD HH:MM:00) between the minimum and maximum when values and whenA being the closest DateTime on or before, and whenB being the closest DateTime on or after the when value? If the exact when value exists, whenA and whenB would be the same as when. If no record on or before, or on or after doesn't exist, NULL will be filled into whenA or whenB, respectively.
Obviously, there are many possible approaches how to make it, but the question is what should be the most efficient one?
You can construct the values using a recursive CTE. Then you can use correlated subqueries to get what you want:
with recursive cte as (
select from_unixtime(floor(unix_timestamp(min(whent)) / 60) * 60) as minw,
max(whent) as maxw
from t
union all
select minw + interval 1 minute, maxw
from cte
where minw < maxw
)
select minw,
(select max(t2.when)
from t t2
where t2.when = cte.minw
) as when,
(select max(t2.when)
from t t2
where t2.when <= cte.minw
) as when_before,
(select min(t2.when)
from t t2
where t2.when >= cte.minw
) as when_after
from cte;
Note that when is a really bad name for a column, because it is a SQL keyword and a reserved word in MySQL.
Here is a db<>fiddle.
I should note that if you have a numbers or tally table of some sort, that could also be used.

MySQL - Keep rows where one entry is a value with multiple occurrences [duplicate]

This question already has answers here:
Select and display only duplicate records in MySQL
(12 answers)
Closed 5 years ago.
So I'm stuck with this problem, and I guess I'm not good enough in MySQL to solve it by myself.
As an example, let's consider this table :
Green entries represent the wanted output of my query, only rows where ENTRY_2 is a value with multiple occurrences are kept.
All I tried for now is something like that :
select *
FROM mytable
GROUP BY ENTRY_2
HAVING COUNT(*) > 1;
But it's not good for obvious reasons (doesn't even work).
Thank you for your time.
I guess
SELECT * FROM mytable WHERE ENTRY_2 IN (
SELECT ENTRY_2
FROM mytable
GROUP BY ENTRY_2
HAVING COUNT(*) > 1
);
is what you want.
I would use exists:
select t.*
from mytable t
where exists (select 1 from mytable t2 where t2.entry2 = t.entry2 and t2.entry1 <> t.entry1);

select a column value from a table only if it has a value assigned else insert a user defined value into that column [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
my requirement is to generate a mysql query as
select ss.column1 P1,ss.column2 P2,ss.column3 P3 from table1 ss;
i want to select column 2 field values only if it has a value in table1 else i want to insert a constant value into the P2 column. Can someone help me with framing a query for this.
COALESCE is the SQL function that let's you replace null values by something else. E.g.:
select
ss.column1 as p1,
coalesce(ss.column2, 'no value') as p2,
ss.column3 as p3
from table1 ss;
The data types must match however, so you can use the above when column2 is a text column. If it is numeric, you can replace null with a numeric value (e.g. with a zero) or you'd cast the columns' datatype.
Some examples:
coalesce(mytext, 'unknown')
coalesce(mynumber, 0)
coalesce(cast(mynumber as varchar), 'unknown')
coalesce(mydate, date(now()))
coalesce(date_format(mydate, '%Y-%m-%d'), 'unknown')

MySQL if statements (with method invocations)? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How do I do the following pseudocode in MySQL:
if (a IS NOT NULL)
{
GROUP BY (id)
num = COUNT(*)
} else {
num = 0
}
Note sure what you are trying to do .....
if you want to count non-null value, check those examples, it would look like this
COUNT(NULLIF(a, ''))
Also consider use Case if you need more complete counting
CASE
WHEN a = 'something' COUNT(1)
ELSE NULL
EDIT
If you want to invoke some query, depend on some value, consider use store procedure/ function
This may be the code you are looking for:
select num := count(distinct id)
from t;
This will set num to 0 if there are no rows.
If you really want the comparison to NULL:
select num := (case when a is not null then count(distinct id) else 0 end)
from t;
Note this assumes that a and num are not columns in the database.

Is there a SQL query that will always return zero results? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
If there is a MySQL/PostgreSQL/Oracle-specific solution, I'm curious about them all.
Depending on the DBMS, one or more of the following will work:
SELECT NULL LIMIT 0 (PostgreSQL and MySQL syntax) / SELECT TOP 0 1 (MS SQL Server syntax)
SELECT NULL WHERE FALSE (DBMS with a boolean type, e.g. PostgreSQL) SELECT NULL WHERE 1=0 (most DBMSes)
For Oracle, these will need to be of the form SELECT NULL FROM DUAL, I believe, as you can't have SELECT without a FROM clause of some sort; not sure which versions of the LIMIT / TOP and WHERE it will accept.
A more elaborate option is to create a (temporary) table and not insert any rows into it, which can give you any number of columns, which will have types associated even though they contain no values:
-- PostgreSQL
CREATE TEMP TABLE dummy ( a Int, b VarChar(42) );
SELECT * FROM dummy;
-- MS SQL Server
CREATE TABLE #DUMMY ( a Int, b VarChar(42) );
SELECT * FROM #DUMMY;
In PostgreSQL, you can even create a table with no columns, allowing you to have a result set with zero rows and zero columns:
CREATE TEMP TABLE empty ();
SELECT * FROM empty;
Another possibility is if the DBMS has set-returning functions, they may be able to return an empty set. For instance, again in PostgreSQL as it's what I know best, you can give an invalid range to generate_series():
SELECT * FROM generate_series(0,-1);
At least in MySQL/PostgreSQL:
SELECT 1 LIMIT 0
select *
from atable
where 1=2
A where value that will always equate to something that is impossible.
Where 1 = 0
Where 'a' = 'b'
etc, etc
There is various answers:
SELECT 1 LIMIT 0
SELECT 1 FROM DUAL WHERE 1=0
However, please notice that even if the number of rows is 0, the number of columns in not.
For example:
INSERT INTO t(a,b) SELECT 1 LIMIT 0;
!! Error: Column count doesn't match value count at row 1
You have to write:
INSERT INTO t(a,b) SELECT 1,1 LIMIT 0;
In PostgreSQL you can:
select
*
from
table
join another_table on (false)
This works because in on() there should be boolean expression. With false the join can be never true.