The table contains 2 columns - the first type is AutoNumber(ID), and the second is Number(Value).
I need to show the ID's of those who their Value is above the average.
How can I do that in the Design view(not with sql, only at the Design view)?
I'm facing following error :
enter image description here
You can use SQL like this:
SELECT id
FROM Table1
,(
SELECT Avg(Table1.num) AS avgnum
FROM Table1
) AS a
WHERE num > a.avgnum;
In design view you can do the same if you create an additional query with average calculation, let's call it qryAvg:
SELECT Avg(Table1.num) AS AvgOfnum
FROM Table1;
Then create another final query, which uses qryAvg:
SELECT Table1.id
FROM Table1, qryAvg
WHERE (((Table1.num)>[AvgOfNum]));
Unfortunately the query builder doesn't allow to work with subqueries in graphic mode, but in such kind simple cases you can avoid using subqueries at all, just use domain aggregate functions instead:
SELECT Table1.id
FROM Table1
WHERE (((Table1.num)>DAvg("num","Table1")));
In this case if num is Long Integer, then you need to cast results of domain function to Long Integer:
SELECT Table1.id
FROM Table1
WHERE (((Table1.num)>CLng(DAvg("num","Table1"))));
Related
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
Is it possible to make a query that changes the where clause acording to some condition? For instance I want to select * from table1 where data is 19/July/2016 but if field id is null then do nothing, else compare id to something else. Like the query bellow?
Select * from table1 where date="2016-07-19" if(isnull(id),"",and id=(select * from ...))
Yes. This should be possible.
If we assume that date and id are references to columns in (the unfortunately named) table table1, if I'm understanding what you are attempting to achieve, we could write a query like this:
SELECT t.id
, t.date
, t....
FROM table1 t
WHERE t.date='2016-07-19'
AND ( t.id IS NULL
OR t.id IN ( SELECT expr FROM ... )
)
It would also be possible to incorporate the MySQL IF() and IFNULL() functions, if there's some requirement to do that.
As far as dynamically changing the text of the SQL statement after the statement is submitted to the database, no, that's not possible. Any dynamic changes to the SQL text would need to be done when the SQL statement is generated, before it is submitted to the database.
My personal preference would be to use a join operation rather than a IN (subquery) predicate.
I think you're trying too hard. If id is NULL that's equivalent to having a FALSE in the where clause. So:
Select * from table1 where date="2016-07-19" and id=(select * from ...)
Should only match the records you want. If id is NULL you get nothing.
I cannot create a virtual table for this. Basically what I have, is a list of values:
'Succinylcholine','Thiamine','Trandate','Tridol Drip'
I want to know which of those values is not present in table1 and display them. Is this possible? I have tried using left joins and creating a variable with the list which I can compare to the table, but it returns the wrong results.
This is one of the things I have tried:
SET #list="'Amiodarone','Ammonia Inhalents','Aspirin';
SELECT #list FROM table1 where #list not in (
SELECT Description
FROM table1
);
With only narrow exceptions, you need to have data in table form to be able to obtain those data in your result set. This is the essential problem that all attempts at a solution to this problem run into, given that you cannot create a temporary table. If indeed you can provide the input in any form or format (per your comment), then you can provide it in the form of a subquery:
(
SELECT 'Amiodarone' AS description
UNION ALL
SELECT 'Ammonia Inhalents'
UNION ALL
SELECT 'Aspirin'
)
(Note that that exercises the biggest of the exceptions I noted: you can select scalars directly, without a base table. If you like, you can express that explicitly -- in MySQL and Oracle, at least -- by selecting FROM DUAL.)
In that case, this should work for you:
SELECT
a.description
FROM
(
SELECT 'Amiodarone' AS description
UNION ALL
SELECT 'Ammonia Inhalents'
UNION ALL
SELECT 'Aspirin'
) a
LEFT JOIN table1
ON a.description = table1.description
WHERE table1.description IS NULL
That won't work. the variable's contents will be treated as a monolithic string - one solid block of letters, not 3 separate comma-separated values. The query will be parsed/executed as:
SELECT ... WHERE "'Amio.....rin'" IN (x,y,z,...)
^--------------^--- string
Plus, since you're just doing a sub-select on the very same table, there's no point in this kind of a construct. You could try mysql find_in_set() function:
SELECT #list
FROM table1
WHERE FIND_IN_SET(Description, #list) <> ''
I am using the following queries and getting diff results.
SELECT SUM(amt) FROM table1 WHERE id in (114,116) and another_id = 10;
result is 10+20 = 30
SELECT SUM(amt) FROM table1 WHERE id in (REPLACE("116,114",'"',"")) and another_id = 10;
result is 10
i was suggested to use a string split function and put the splits in a table,can someone point me to an example?
SELECT SUM(amt)
FROM table1
WHERE id in (REPLACE("116,114",'"',"")) and another_id = 10;
It would help if we knew what you were trying to do.
At a guess, I suspect that you want to provide a facility where someone can specify a set of ids and pass that as an argument to the query.
A simple solution would be:
WHERE CONCAT('%,', id, ',%') LIKE ('${submitted_string}')
But this will not be able to use any index on table1.id
AFAIK there's no way to cast an array/string to a table type in MySQL, so you'd need to parse the string and put the values temporaril;y into a table along with a key referencing the session (or into a temporary table). Doing this in SQL is rather hard work - it's a lot simpler to use a logic tier on top - which, based on my interpretation of what your trying to achieve you must already have.
Based on your code, it appears ID is a numeric field...
Try this for the second example...
SELECT SUM(amt) FROM table1 WHERE ","+CAST(id AS CHAR)+"," in (","+"116,114"+",")
and another_id = 10;
I'm working on a very limited MySQL environment (all MySQL calls are passed as array parameters). The problem is I don't know how to resolve an ambiguos condition.
In this environment all MySQL calls take this form:
SELECT value1,value2,...,valueN
FROM table1,table2,...,tableN
WHERE cond1 OP cond2 OP ... OP condN
That's not a problem until you have the same column names in table1 and table2. Imagine table1 has columns {a,b,z} and table2 has column names {c,d,f,z}. I can do this:
SELECT *
FROM table1, table2
WHERE a='3' AND table1.z='5'
Perfect but, one of the limitations is that I can't use table1.z format, just z='5' that produces a collision.
So, the question is: is there any way to prevent this ambiguosity without the use of table name prefix in the condition part? (for example, it will be great if there is a way to use only part of table2 or say that table1 has priority in case of ambiguity).
There is no way to avoid a collision if you can't qualify which table "myColumn" comes from.
Your constraints seem kind of silly... You're basically asking for valid result when you assert that you cannot write valid SQL....
Perhaps instead of SELECTing from table1, you would SELECT from a nested subquery in which you aliased the column names...
For example:
if table1 and table2 both have column "myColumn"
Rather than:
SELECT
*
FROM
table1,table2
WHERE myColumn = #value -- produces collision!
Could you say:
SELECT
*
FROM
(SELECT myColumn AS foo FROM table1) newTable1,
(SELECT myColumn AS bar FROM table2) newTable2
WHERE
foo = #value
This way you're not fully qualifying the tables in the outer WHERE clause but you are re-aliasing the columns inside the subqueries (thus making them into different names for the outer query)
This seems like a roundabout exercise though
EDIT:
http://thedailywtf.com/Articles/SQL-Sentences.aspx
"MySQL sentences?"