How to use the same function like Oracle Rownum in MS ACCESS - sql

I am encountering a problem, I had done a function that the data can be loaded by detecting scrolling position, the function was made with a SQL statement "Rownum", it only works in Oracle, but not in ACCESS.
I would like to query the data and resort it
ID value
1 aa
3 bb
with Rownum we can do like this
NID ID value
1 1 aa
2 3 bb
how can I write a SQL statement with Microsoft ACCESS

Access does not support that function. If your ID field is a numeric primary key, you can include a field expression which is the count of the number of rows with ID <= to the current ID value.
SELECT
DCount('*', 'YourTable', 'ID <= ' & y.ID) AS NID,
y.ID,
y.value
FROM YourTable AS y;
You could use a correlated subquery instead of DCount if you prefer.
And ID does not actually have to be a primary key. If it has a unique constraint it is still suitable for this purpose.
And the targeted field does not absolutely have to be a number, but text data type can be more challenging.

Related

Redshift - CASE statement checking column EXISTS or no

I am querying dynamically tables where some of the tables might not have specific column. My intention is check the existence of the column and dynamically assign a value. Basically if all the tables would contain the field I would just write simply :
select name, count(k_val) from tbl GROUP by 1
But in my case I need to do something like this:
select name,
SUM( (CASE when (select EXISTS( SELECT * FROM pg_table_def WHERE tablename = 'tbl'
and "column" = 'k_val'))
then 1 else 0 end) ) as val
from tbl GROUP by 1
I am getting the error:
SQL Error [500310] [0A000]: Amazon Invalid operation:
Specified types or functions (one per INFO message) not supported on
Redshift tables.;
The following is a trick that works on most databases to handle missing columns.
select t.*,
(select k_val -- intentionally not qualified
from tbl t2
where t2.pk = t.pk
) new_k_val
from tbl t cross join
(select NULL as k_val) k;
pk is the primary key column for the table. This uses scoping rules to find a value for k_val. If k_val is in the table, then the subquery will use the value from that row. If not, then the scope will "reach out" and take the value from k. There is no confusion in this case, because k_val is not in tbl.
If you don't want a constant subquery for some reason, you can always use:
(select NULL as k_val from t limit 1) k
You can then use this as a subquery or CTE for your aggregation purposes.
Having said all that, I am wary of handling missing columns this way.

How to get a list of unused/available primary keys (primary key ranges from 1 to 999) in an Oracle SQL table?

I have employee table where primary key empl_no ranges from 1 to 999. Now I want to know what primary_key are still available for adding new employee(s). For example, below query returns the value 993. That means there are still 6 empl_no availavle which have not been used yet. How can I get the list of those 6 available empl_no using Oracle SQL? Thanks in advance for you help :)
SELECT count(empl_no)
FROM emplpyee
WHERE empl_no BETWEEN 1 AND 999;
WITH cteNumbers AS (
SELECT LEVEL AS NUM
FROM DUAL
CONNECT BY LEVEL <= 999
)
SELECT n.NUM
FROM
cteNumbers n
LEFT JOIN emplpyee e
ON n.Num = e.empl_no
WHERE
e.empl_no IS NULL
Again don't re-use primary keys! But if you really want to know what is missing use a numbers table. In ORACLE they make it easy using CONNECT BY. Then LEFT JOIN back to your table and look for when the empl_no is missing.
here is a link that shows oracle's ability to create a numbers table on the fly:
http://rextester.com/CZDKC69208
select level from dual connect by level <= 999
minus
select empl_no from emplpyee
Subtract all IDs found in the table from all available IDs. You create all available IDs by determining the number range first (number(3) i.e. 0 to 999 in your case) and then recursively create all numbers in that range.
In standard SQL (and in Oracle as of version 11.2) you'd use a recursive CTE for this.
with all_ids(id) as
(
select power(10, data_precision) - 1 as id from all_tab_cols
where owner = 'HR' and table_name = 'EMPLOYEES' and column_name = 'EMPLOYEE_ID'
union all
select id - 1 from all_ids where id > 0
)
select id from all_ids
minus
select employee_id from employees;
I am assuming that your table consists some columns X,Column Y other than empl_no.So to find an available primary key you need to find the of rows which are NULL for column X and Y (that means they are empty).Below query might help..
SELECT empl_no FROM emplpyee WHERE columnX IS NULL and columnY IS NULL

Randomly Select a Row with SQL in Access

I have a small access database with some tables. I am trying the code in the sql design within access. I just want to randomly select a record within a table.
I created a simple table called StateAbbreviation. It has two columns: ID and Abbreviation. ID is just an autonumber and Abbreviation are different abbreviations for states.
I saw this thread here. So I tried
SELECT Abbreviation
FROM STATEABBREVIATION
ORDER BY RAND()
LIMIT 1;
I get the error Syntax error (missing operator) in query expresion RAND() LIMIT 1. So I tired RANDOM() instead of RAND(). Same error.
None of the others worked either. What am I doing wrong? Thanks.
Ypercude provided a link that led me to the right answer below:
SELECT TOP 1 ABBREVIATION
FROM STATEABBREVIATION
ORDER BY RND(ID);
Note that for RND(), I believe that it has to be an integer value/variable.
You need both a variable and a time seed to not get the same sequence(s) each time you open Access and run the query - and to use Access SQL in Access:
SELECT TOP 1 Abbreviation
FROM STATEABBREVIATION
ORDER BY Rnd(-Timer()*[ID]);
where ID is the primary key of the table.
Please try this, it is helpful to you
It is possible by using a stored procedure and function, which I created it's have a extra column which you could be create in your table FLAG name and column all field value should be 0 Then it works
create Procedure proc_randomprimarykeynumber
as
declare #Primarykeyid int
select top 1
#Primarykeyid = u.ID
from
StateAbbreviation u
left join
StateAbbreviation v on u.ID = v.ID + 1
where
v.flag = 1
if(#Primarykeyid is null )
begin
UPDATE StateAbbreviation
SET flag = 0
UPDATE StateAbbreviation
SET flag = 1
WHERE ID IN (SELECT TOP 1 ID
FROM dbo.StateAbbreviation)
END
ELSE
BEGIN
UPDATE StateAbbreviation
SET flag = 0
UPDATE StateAbbreviation
SET flag = 1
WHERE ID IN (#Primarykeyid)
END
SET #Primarykeyid = 1
SELECT TOP 1
ID, Abbreviation
FROM
StateAbbreviation
WHERE
flag = 1
It is made in stored procedure run this and get serial wise primary key
exec proc_randomprimarykeynumber
Thanks and regard
Try this:
SELECT TOP 1 *
FROM tbl_name
ORDER BY NEWID()
Of course this may have performance considerations for large tables.

How do I query the set of UUIDs trimmed to the smallest unique prefix?

I have a SQLite database which stores UUIDs as the keys. UUIDs are very long and so for usability I have implemented a function which autocompletes a UUID prefix to the full UUID value (or returns NULL on non-unique prefix).
I was wondering if there is a query which can return the set of UUID prefixes such that each prefix is unique. This includes two cases: the one where each UUID prefix is the smallest size it can possibly be and the case that all UUID prefixes are the length of the longest UUID prefix needed for uniqueness.
For example if the data is:
AB1234DE...
AA1264DE...
BA2234DE...
The set of minimal prefixes would be:
AB
AA
B
The set of prefixes with the length necessary for uniqueness:
AB
AA
BA
Any idea how to accomplish this in a SQLite query? (the column is named id)
This could be implemented using analytic functions that for example Oracle DBMS has, but in sqlite there is no way to write such complex logic in sql query.
The possible shorthand I could propose to use is:
SELECT COUNT(*) as cnt
FROM tbl
GROUP BY SUBSTR(id, 0, 1)
HAVING COUNT(*) > 1
And increase the length of string in your programming language until this query returns no rows (or you can even make nested query) like:
SELECT IF(COUNT(*) > 0, 'Duplicates found', 'No duplicates') AS result FROM (
SELECT 1
FROM tbl
GROUP BY SUBSTR(id, 0, 1)
HAVING COUNT(*) > 1
)
and increase substring length until result is not desired

formula for computed column based on different table's column

Consider this table: c_const
code | nvalue
--------------
1 | 10000
2 | 20000
and another table t_anytable
rec_id | s_id | n_code
---------------------
2 | x | 1
The goal is to have s_id be a computed column, based on this formula:
rec_id*(select nvalue from c_const where code=ncode)
This produces an error:
Subqueries are not allowed in this context. Only scalar expressions are allowed.
How can I calculate the value for this computed column using another table's column as an input?
You could create a user-defined function for this:
CREATE FUNCTION dbo.GetValue(#ncode INT, #recid INT)
RETURNS INT
AS
SELECT #recid * nvalue
FROM c_const
WHERE code = #ncode
and then use that to define your computed column:
ALTER TABLE dbo.YourTable
ADD NewColumnName AS dbo.GetValue(ncodeValue, recIdValue)
This seems to be more of a job for views (indexed views, if you need fast lookups on the computed column):
CREATE VIEW AnyView
WITH SCHEMABINDING
AS
SELECT a.rec_id, a.s_id, a.n_code, a.rec_id * c.nvalue AS foo
FROM AnyTable a
INNER JOIN C_Const c
ON c.code = a.n_code
This has a subtle difference from the subquery version in that it would return multiple records instead of producing an error if there are multiple results for the join. But that is easily resolved with a UNIQUE constraint on c_const.code (I suspect it's already a PRIMARY KEY).
It's also a lot easier for someone to understand than the subquery version.
You can do it with a subquery and UDF as marc_s has shown, but that's likely to be highly inefficient compared to a simple JOIN, since a scalar UDF will need to be computed row-by-row.