sqlite select query top X% for every item - sqlite

i making get topX% query
SELECT CAST(ROUNT(COUNT(*) * 0.1)AS INTEGER) FROM person;
But syntax error ,,
This is the kind of query I want to finally make.
SELECT*FROM person
ORDER BY vote DESC LIMIT (SELECT CAST(ROUNT(COUNT(*) * 0.1)AS INTEGER)
FROM person);
how to fix it ?

Related

how to return something else when nothing is found?

My current query:
select timestamp from messagesTable
where partner_jid='" + lastUserJid + "' AND msg='.roll'
order by timestamp DESC LIMIT 1 OFFSET 1;
This works fine... unless the values don't exist in the database.
If values do not exist in database, then it should Select * messagesTable; or do nothing if possible.
Is there a way to add a check for that within the same query? It has to be the same query unfortunately because I need to execute things through adb shell. I've been trying things out with CASE but I do not really understand much about SQL.
You can just append a second query, with a WHERE filter that checks whether the first query did not return anything:
SELECT *
FROM (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll'
ORDER BY timestamp DESC
LIMIT 1 OFFSET 1)
UNION ALL
SELECT -1 -- or "timestamp FROM msgTab", or whatever
WHERE NOT EXISTS (SELECT timestamp
FROM messagesTable
WHERE partner_jid = ?
AND msg = '.roll');

pass curosr variable to subquery in cirsor iterating loop

1 what is my purpose:
I try to get two person from each department with highest salary.
2 how I try to achieve it:
DECLARE
TYPE empl_table IS TABLE OF employees.employee_id%type INDEX BY binary_integer;
empl empl_table;
CURSOR departmennts_id IS
SELECT department_id FROM departments;
BEGIN
FOR depart_row IN departmennts_id
loop
SELECT employee_id BULK COLLECT into empl
FROM
(
SELECT employee_id
FROM employees
where DEPARTMENT_ID= depart_row.department_id
ORDER BY salary DESC
)
WHERE ROWNUM<3;
END loop;
END;
3 where is the problem:
where DEPARTMENT_ID= depart_row.department_id
When I change depart_row.department_id for fixed id number(ex. 80)
query works. If I use depart_row.department_id empl.count is 0.
Where I am making mistake?
For each iteration of your outer cursor you're putting rows into EMPL_TABLE. Each time that the code loops back for another department_id and then re-executes the inner SELECT it replaces the contents of the collection. Thus, if the LAST department seen by the outer cursor happens to have no employees associated with it, you end up with an empty collection.
Your best bet is to eliminate the separate cursor on DEPARTMENTS and just use a single cursor that does everything you want, as in:
SELECT *
FROM (SELECT DEPARTMENT_ID,
SALARY,
ROW_NUMBER() OVER
(PARTITION BY DEPARTMENT_ID
ORDER BY SALARY DESC) AS EMP_RANK
FROM EMPLOYEES
ORDER BY DEPARTMENT_ID, EMP_RANK)
WHERE EMP_RANK < 3
SQLFiddle here.
Share and enjoy.

Different Data types Order By in SQL

I have one situation where i want to sort table on from time but if the status of the row is suppose abc i want to order by these records by status.
Requirement is all vacant records needs to be display at the bottom and after that in top records i have to display records as per from time asc.
status is varchar , fromtime is decimal
e.g. status- vacant,occupied,current etc.
fromtime- 13.00,14.30,07.30 etc.
select * from tbluser order by case when [status]='vacant' then [status] else fromtime end
i am getting below error
Conversion failed when converting the varchar value 'vacant' to data type int
i have 2 columns one with integer and one with varchar. works with varchar. but not with decimal
but when i use below condition it works
[from time] is varchar-
Case When Status = 'Vacant' Then Status Else [from time] End
use cast in your query as cast(fromtime as varchar)
So your query becomes
select
*
from
tbluser
order by
case
when [status]='vacant' then [status]
else cast(fromtime as varchar) end
Edit 1
Here is a similar post which may help you
Understanding a Sql Server Query - CASE within an ORDER BY clause
SELECT *
FROM tbluser
ORDER BY CASE
WHEN [status]='vacant' then [status]
ELSE CONVERT(VARCHAR(max), fromtime)
END

How to select latest Row from table without using ORDER BY

How can I select latest row from by table without sorting it?
It is because it follow by the ID AUTO INCREMENT...
I'm using c# asp.net to select... I did try using LIMIT 5 but it give me an error page..
rSQL = "select COUNT(*) from chatLog_db where sessionid='" + grpID + "' LIMIT 5";
Is there any better way to solve this matter?
I'd appreciate any help please.
You have an id column which is autoincremented, right? Then you can do it like this..
select * from tablename where id=(select MAX(rid) from tablename)
On MSSQL simply use the top 1 instead of limit
select top(1) * from mytable order by some_column
http://msdn.microsoft.com/en-us/library/ms189463.aspx
if the latest means the max id
select * from chatLog_db
where id = (select max(id) from chatLog_db);
EDIT
select 5 records
select * from chatLog_db
where id > (select max(id) - 5 from chatLog_db);
You can try
SELECT * FROM chatLog_db WHERE sessionid > (SELECT MAX(sessionid) - 1 FROM chatLog_db);
You may also try for
SELECT * FROM chatLog_db WHERE sessionid > (SELECT MAX(sessionid) - 5 FROM chatLog_db);
You may use max as well like
select * from chatLog_db where sessionid = (select max(sessionid) from chatLog_db);
Something like that.
If you are not using order by into your query because you are thinking that it will change the order of your dsplay data then i will tell you that there is one trick as well to sort your data as per your need
you can also sort your data as per your need even if you are using
order by into your query,put the result into DataView and sort it
according to your need because DataView allow us sorting facility as
well.
Latest by using Order By like
select * from tablename order by columnname desc LIMIT 5;
Hope it works for you.

PL/SQL - comma separated list within IN CLAUSE

I am having trouble getting a block of pl/sql code to work. In the top of my procedure I get some data from my oracle apex application on what checkboxes are checked. Because the report that contains the checkboxes is generated dynamically I have to loop through the
APEX_APPLICATION.G_F01
list and generate a comma separated string which looks like this
v_list VARCHAR2(255) := (1,3,5,9,10);
I want to then query on that list later and place the v_list on an IN clause like so
SELECT * FROM users
WHERE user_id IN (v_list);
This of course throws an error. My question is what can I convert the v_list to in order to be able to insert it into a IN clause in a query within a pl/sql procedure?
If users is small and user_id doesn't contain commas, you could use:
SELECT * FROM users WHERE ',' || v_list || ',' LIKE '%,'||user_id||',%'
This query is not optimal though because it can't use indexes on user_id.
I advise you to use a pipelined function that returns a table of NUMBER that you can query directly. For example:
CREATE TYPE tab_number IS TABLE OF NUMBER;
/
CREATE OR REPLACE FUNCTION string_to_table_num(p VARCHAR2)
RETURN tab_number
PIPELINED IS
BEGIN
FOR cc IN (SELECT rtrim(regexp_substr(str, '[^,]*,', 1, level), ',') res
FROM (SELECT p || ',' str FROM dual)
CONNECT BY level <= length(str)
- length(replace(str, ',', ''))) LOOP
PIPE ROW(cc.res);
END LOOP;
END;
/
You would then be able to build queries such as:
SELECT *
FROM users
WHERE user_id IN (SELECT *
FROM TABLE(string_to_table_num('1,2,3,4,5'));
You can use XMLTABLE as follows
SELECT * FROM users
WHERE user_id IN (SELECT to_number(column_value) FROM XMLTABLE(v_list));
I have tried to find a solution for that too but never succeeded. You can build the query as a string and then run EXECUTE IMMEDIATE, see http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/dynamic.htm#i14500.
That said, it just occurred to me that the argument of an IN clause can be a sub-select:
SELECT * FROM users
WHERE user_id IN (SELECT something FROM somewhere)
so, is it possible to expose the checkbox values as a stored function? Then you might be able to do something like
SELECT * FROM users
WHERE user_id IN (SELECT my_package.checkbox_func FROM dual)
Personally, i like this approach:
with t as (select 'a,b,c,d,e' str from dual)
--
select val
from t, xmltable('/root/e/text()'
passing xmltype('<root><e>' || replace(t.str,',','</e><e>')|| '</e></root>')
columns val varchar2(10) path '/'
)
Which can be found among other examples in Thread: Split Comma Delimited String Oracle
If you feel like swamping in even more options, visit the OTN plsql forums.

Resources