Query to finding duration of a value
Hi,
I have a table like below
Create table Datachange(device id , Status Bit , Changed_at datetime);
insert into datachange values (100, 1, '2015-03-21 19:30:16.440'), (100, 0, '2015-03-22 20:31:06.440'), (100, 1, '2015-03-25 20:31:06.440');
I am in need of a sql query to get the duration of status 1 and status 0 between given two date periods for the device For eg. I may give the input from and to period may be between 21 to 25th march 2015 (or) 23rd to 24th march 2015 ..
>> I have a table like below <<
This is not a table. It has no key, no way to ever have a key and the data types are wrong. We do not use assembly language bit flags in SQL. What you have done is copy a paper log sheet into a non-table! If you had a read a book on data modeling,
you would know that a status is a “state of being” so it has to have a temporal dimension, a duration, and not a single point in time. I am also going to guess that you do not need nanoseconds, and that whole dates will work.
CREATE TABLE Device_History
(device_name CHAR(5) NOT NULL,
device_status CHAR(3) NOT NULL
CHECK (device_status IN ('IN', 'OUT')),
start_timestamp DATE NOT NULL,
end_timestamp DATE,
CHECK (start_timestamp <= end_timestamp),
PRIMARY KEY (device_name, start_timestamp));
We can put more constraints to control the gaps and other things but I do not think you are ready for them yet.
INSERT INTO Device_History
VALUES
('D-100', 'IN', '2015-03-21', '2015-03-21'),
('D-100', 'OUT', '2015-03-22', '2015-03-24'),
('D-100', 'IN', '2015-03-25', NULL);
>> I am in need of a SQL query to get the duration of status 'IN' and status 'OUT' between given two date periods for the device <<
And now with a valid design, your problem is trivial! I estimate that 85-95% of the work in SQL should be done in the DDL. Please read any book on RDBMS and then one on basic data modeling.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Similar Messages
-
Need helping in writing query for finding percentage of duration
Can any one please help in writing query for this.
The table is like this :-
ID Region Month Duration
I1 R1 Jan 80
I2 R2 Jan 70
I3 R1 Jan 70
I4 R3 Jan 40
I5 R1 Feb 80
I6 R2 Feb 30
I7 R3 Mar 100
I want to write a query to find
% of duration for each and every region against each and every month.
Please help in solving this query. I am in urgent need of this.
Thanks in advance.I also have to do in MS Access 2003You also have to ask into an other forum since here it's an Oracle forum, to try to find Oracle solution.
Nicolas. -
Write the sql query to find largest value in row wise without using great
write the sql query to find largest value in row wise without using
greatest fuction?Another not so good way, considering you want greatest of 4 fields from a single record:
SQL> ed
Wrote file afiedt.buf
1 with t as (Select 100 col1,200 col2,300 col3,400 col4 from dual
2 union select 500,600,700,800 from dual
3 union select 900,1000,1100,1200 from dual
4 union select 1300,1400,1500,1600 from dual
5 union select 1700,1800,1900,2000 from dual
6 union select 2100,2200,2300,2400 from dual
7 union select 2800,2700,2600,2500 from dual
8 union select 2900,3000,3100,3200 from dual)
9 SELECT (CASE WHEN col1 > col2 THEN col1 ELSE col2 END) Max_value
10 FROM
11 (SELECT (CASE WHEN col1_col2 > col2_col3 THEN col1_col2 ELSE col2_col3 END) col1,
12 (CASE WHEN col2_col3 > col3_col4 THEN col2_col3 ELSE col3_col4 END) col2,
13 (CASE WHEN col3_col4 > col4_col1 THEN col3_col4 ELSE col4_col1 END) col3
14 FROM
15 (SELECT (CASE WHEN col1 > col2 THEN col1 ELSE col2 END) col1_col2,
16 (CASE WHEN col2 > col3 THEN col2 ELSE col3 END) col2_col3,
17 (CASE WHEN col3 > col4 THEN col3 ELSE col4 END) col3_col4,
18 (CASE WHEN col4 > col1 THEN col4 ELSE col1 END) col4_col1
19* FROM t))
SQL> /
MAX_VALUE
400
800
1200
1600
2000
2400
2800
3200
8 rows selected.
SQL> Edited by: AP on Sep 21, 2010 6:29 AM -
How to find out the ASCII Values for Spanish character
Hi,
I had an requirement to store Spanish character and also need to fileter the records based on the Spanish character.
Kindly guide me for below.
To filter the Records which contains spanish characters?
To get the ASCII Values for the particular column?
E.g. we can find out the ASCII value of 'a' by using the syntax select ASCII('a') from dual.
But I want to find the ASCII Values for the particular column value. Ie. name.
E.g., Client name is "Suresh", I want to the ASCII Values for entire name of "Suresh".
Kindly do the needful help / Guidance on this.
Thanks,
OraharTo expand on what I said in my first post, you want to do something along these lines:
with t (thename) as
select 'Suresh' from dual
select thename
, substr(TheName, level, 1)
, ascii(substr(thename, level))
from t
connect by level <= length(thename);The output of the above query is:
THENAM S ASCII(SUBSTR(THENAME,LEVEL))
Suresh S 83
Suresh u 117
Suresh r 114
Suresh e 101
Suresh s 115
Suresh h 104
6 rows selected.Note that the WITH statement is only there to simulate a table for this example. With a table, all you do is get rid of the with and substitute the name "t" for the name of your table (also the name of the column to whatever name the column has in your table).
Lastly, I suggest you post your question along with, an example table and the output you'd like to get in the PL/SQL forum. There are people there that will give you all kinds of great ways of solving that problem.
HTH,
John. -
Query to find out two counts on each column
Hi
can you help for the below query.
I wanted to find out two count values on each column, ie above or equal 5 count and below 5 count.
Table:
Q1 Q2 Q3 (Q1, Q2, Q3 are columns in a table.)
1 3 5
6 7 4
8 5 1
2 8 5
Query should display, like below.
Expected Result:
colname >=5 count <5 count
Q1 2 2
Q1 3 1
Q3 2 2
Thanks in advance.The query itself can be simplified as follows:
SQL> with t as (
2 select level lvl from dual
3 connect by level < 4)
4 select colname
5 , sum(case when val >= 5 then 1 else 0 end) "count >= 5"
6 , sum(case when val < 5 then 1 else 0 end) "count < 5"
7 from (
8 select decode (lvl, 1, 'Q1', 2, 'Q2', 'Q3') colname
9 , decode (lvl, 1, q1, 2, q2, q3) val
10 , lvl
11 from (select q1, q2, q3
12 from q),
13 t)
14 group by colname, lvl
15 order by lvl;Lines 8-10 is what pivots the cartesian join (CJ) of q & t. It helps to explain it by breaking down each part.
The CJ produces (I added the lvl into the output below for explanation purposes):
SQL> with t as (
2 select level lvl from dual
3 connect by level < 4)
4 select q1, q2, q3, lvl
5 from q,
6 t;
Q1 Q2 Q3 LVL
1 3 5 1 <-- line a1
6 7 4 1 <-- line a2
8 5 1 1
2 8 5 1
1 3 5 2 <-- line a5
6 7 4 2
8 5 1 2
2 8 5 2
1 3 5 3
6 7 4 3
8 5 1 3
2 8 5 3
12 rows selected.and the CJ from above now allows us to pivot the results using the LVL column as the "decoding" key.
SQL> with t as (
2 select level lvl from dual
3 connect by level < 4)
4 select decode (lvl, 1, 'Q1', 2, 'Q2', 'Q3') colname
5 , decode (lvl, 1, q1, 2, q2, q3) val
6 , lvl
7 from (select q1, q2, q3
8 from q),
9 t;
COLNAME VAL LVL
Q1 1 1 <-- line b1
Q1 6 1 <-- line b2
Q1 8 1
Q1 2 1
Q2 3 2 <-- line b5
Q2 7 2
Q2 5 2
Q2 8 2
Q3 5 3
Q3 4 3
Q3 1 3
Q3 5 3
12 rows selected.Line b1:
The decodes hit line a1 of the CJ and since lvl = 1, we get colname=Q1 and the corresponding Q1 row value (val=1) of line a1 and finally the value of 1 for lvl.
Line b2:
For decode of line a2 of the CJ, lvl = 1 again and we get colname=Q1 and the corresponding Q1 row value (val=6) of line a2 and finally the value of 1 for lvl.
Line b5:
For decode of line a5 of the CJ, lvl = 2 and we get colname=Q2 and the corresponding Q2 row value (val=3) of line a5 and finally the value of 2 for lvl.
The other rows of the pivoted result set above are obtained similarly and from this result we can now perform the aggregation for the final result.
The WITH query is a called subquery factoring. It allows you to reference the subquery multiple places in the query.
HTH -
Query to find out which process consuming more cpu?
Hi All,
some one please tell me the query to find out which process is consuming more
cpu resources?
Thanks and Regards
SrikanthUse V$SESSTAT to determine which sessions are using most CPU, and investigate what SQL these users/sessions are executing:
SQL> select ss.sid, se.command, ss.value CPU, se.username, se.program
from v$sesstat ss, v$session se
where ss.statistic# in
(select statistic#
from v$statname
where name = 'CPU used by this session')
and se.sid=ss.sid
order by ss.value desc; -
Query to find customers who have not purchased anything
I have a query to find customers who have purchased what we call consumables (using item property) over a given period:
SELECT T0.CardCode, T0.CardName, T0.DocDate, T0.DocTotal, T1.ItemCode, T1.Dscription,T1.quantity, T2.ItmsGrpNam
FROM OINV T0 INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry, OITG T2
WHERE T0.DocDate BETWEEN '[%0]' AND '[%1]' AND T1.ItemCode like '2ssy%' AND T2.ItmsGrpNam = 'consumable'
I have another to show customers who have a particular type of equipment:
SELECT T0.manufSN,T0.itemName, T3.Name, T2.Address, T2.Street, T2.Block, T2.City, T2.County, T2.ZipCode
FROM OINS T0 INNER JOIN OCRD T1 ON T0.customer = T1.CardCode INNER JOIN CRD1 T2 ON T1.CardCode = T2.CardCode Inner Join OCPR T3 ON T0.ContactCod = T3.CntctCode
WHERE T0.manufSN like 'P%' AND T2.AdresType= 'S'
What I would like is to find those customers who have this equipment (query 2) but who have NOT purchased and consumables in say the last year.
I have tried using Excel by finding duplicates and taking those in query 1 from those in query 2 but it's very messy.
Has anyone done anything like this or got any good ideas?
ThanksHi Ralph,
Well, I enjoy teaching, so let's start at the beginning. SQL is a fairly full-featured language, and it supports recursion and nesting. That's why the books online often describe elements of the SQL statements as "expression" - it may be more than a field or a simple function occurring there. Nesting is the little puppy we used here.
Now, in your first post, you said: "What I would like is to find those customers who have this equipment (query 2) but who have NOT purchased and consumables (query 1) in say the last year."
So, our common point between the two queries is the customer, the CardCode. That's what this part does: F0.CardCode = T0.Customer. In my internal convention, I used F for Filter. So we only want the results in the filter where the CardCode matches the CardCode/Customer from the main query tables. It's the sole contact point between the two queries.
You also said you wanted only the items where they had purchased no consumables, which basically translates into: a count of the records equals 0. Now, since all we're interested in from the second query, the consumables query is how many records we returned, we get rid of all the columns except for one that we apply a COUNT to. After that, it's a simple criteria: the result of the second query has to equal 0. This is how the criteria looks after you take out all the details and put only the important brackets in: (SELECT COUNT...FROM...WHERE...) = 0.
This might be confusing at first, because most of the time we return recordsets from queries, but a standard feature of SQL is to return a value of any data type if the query returns a single row and a single column. This wouldn't work at all if we had more than one column in our nested query (or would require lots of tweaking), and although it returns a number of results in the complete process of the whole SQL statement, it only returns one result for each row.
Regards,
Mark Dielmann
Edited by: Mark Dielmann on Nov 13, 2009 12:30 PM - Forum doesn't support advanced formatting on answered questions.
Edited by: Mark Dielmann on Nov 13, 2009 12:32 PM - Salutations and more formatting.
Edited by: Gordon Du on Nov 13, 2009 10:35 AM - There are maximum characters limitation for correct format -
How to find if COLUMN DEFAULT VALUE is stored as metadata?
Hello,
I'm using Oracle 11g enhanced ADD COLUMN Functionality. Adding new columns with DEFAULT values and NOT NULL constraint no longer requires the default value to be stored in all existing records.
Sometimes we change DB columns from NOT NULL with DEFAULT to NULL with DEFAULT. This operation "materialize" column default.
Is there an easy way (Dictionary view) how to find, that COLUMN default value is stored as metadata or is "materialized" ?
Thanks. Filip
Oracle RDBMS version : Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit ProductionThanks for your suggestion, but it is not what i'm looking for :-(
I don't need to find the default value, i need to know how is default value stored. It could be stored in 2 ways.
1. "materialized" - prior to 11G (value is physicaly stored for every column)
2. "as a metadata" - new 11G functionality (default is not physicaly stored and if you query the column DB transalte NULL value to defaut value)
Now I would like to now if my column is type 1) or 2). How can I do it?
Thank you.Filip -
WARNING: ADFv: Could not find selected item matching value ...
Using Windows JDev 11.1; I have an entity object with an attribute which has a LOV configured to supply a select-one-choice render. The LOV query requires that a bind variable be supplied. When creating a new record in the entity via the VO, I can use the ViewImpl to create a new row, retrieve the RowSet which corresponds to the attribute LOV query, set the named where clause parameter, and I'm away. When updating however, I'm getting the following error reported:
09/12/2009 2:44:04 PM oracle.adfinternal.view.faces.model.binding.FacesCtrlListBinding getInputValue
WARNING: ADFv: Could not find selected item matching value EMPLOYER of type: java.lang.String in the list-of-values.
I can't supply the bind variable value before the row is instantiated (and presumably populated with the current value/key) because the View Accessor RowSet is only accessible via the RowImpl. If after the query has executed, I apply the bind variable value, re-execute the RowSet query, I can see that it's populated, and I can create a RowSetIterator to loop through the LOV RowSet and confirm that the key/value is there. I can even setCurrentRow on the RowSet but I still find that the above error appears in the serve log output seemingly after all this code executes.
So my question is what is the technique for supplying bind variables to attribute LOV View Accessors as part of an underlying EO object query.
In the run-time, the list items appear unpopulated (current value and list items). If I reload the page, it all comes up fine, which could tend to suggest that a PPR event might fix me up, but I would prefer to know how this should be done.
Thanks in advance.
Edited by: robli on Dec 9, 2009 9:01 PMHi,
Is your issue resolved. I'm facing similar issue. I have created a viewaAccessors in EO, associated these to ViewObject attributes as List of Values.
I created the table in UI using the ViewObject.
I see those as selectOneChoice but not values (Empty list).
If I create new record in the table by CreateInsert. table now shows the ListOfvalues.
any Idea what am I missing.
Thanks,
Satya
Edited by: stammine on Mar 2, 2010 4:09 PM -
SQL query to find out last login for each database
Hi everybody,
I have a view with following columns:
DatabaseSid, lastLogin, firstLogin.
I want to now the newest last_login date for every database.
SID First Login Last Login
e.g. Database1, 11.11.2011, 01.12.2011
Database1, 01.04.2012, 01.05.2012
Database3, 03.03.2004, 03.06.2005
Database 3 07.09.2012, 12.10.2012
How can I do a query to find out for eacht DB (DB1, DB2 and so on) the Last_Login Date?
Thank you in advance
SteveSteve wrote:
Hi everybody,
I have a view with following columns:
DatabaseSid, lastLogin, firstLogin.
I want to now the newest last_login date for every database.
SID First Login Last Login
e.g. Database1, 11.11.2011, 01.12.2011
Database1, 01.04.2012, 01.05.2012
Database3, 03.03.2004, 03.06.2005
Database 3 07.09.2012, 12.10.2012
How can I do a query to find out for eacht DB (DB1, DB2 and so on) the Last_Login Date?
Thank you in advance
SteveI'm curious as to how you collect this information from multiple databases into one database, and of what value the data is once you have it. -
Handle Query when he doesn't return value
hello,
I have this code in a WBP
begin
go_block('xxx');
execute_query;
end;
and in my 'xxx' block i have a pre-query that makes a set_block_property('xxx',defaut_where,value);
but when my query doesnt find any record he still continues to run untill he returns me somes wrong records. how i know? I checked in backend with the condition values and there are no records for these condition values. so i think it's may be because i didn't handle my query for when he doesn't find records that match with the condition.
if some cn tell me what to do and where to do it to resolve this problem, it will be nice to him.
thanks
Charlyuser10131488 wrote:
Hello,
Sorry to ask you that, but i tried to retrieve the last query in the system variable, but i can't. first i create an item and create a WMC trigger and i put this code in it:
DECLARE
tempv VARCHAR2(500);
BEGIN
tempv:=:SYSTEM.LAST_QUERY;
:GPV_OBJECTIF.TEXT_ITEM326:=temp;
END;
i received an error that there is an exception that not handle. when i click on this item nothing happened.
may be i placed the code in the wrong trigger.
also i checked my query carefully, it seems everything is all rigth.
CharlyMouse triggers are intentionally ignored in WebForms, they will not fire.
you need to use some other trigger or a button or a message. What is the error you got?? you probably need to use a variable greater than VARCHAR2(500), try using VARCHAR2(4000) just to be on the safe side.
Tony -
Query to find the application user
Hi,
what is the query to find the application user in sql command?
I tried the below query
select app_user from dual;
app_user invalid identifierthanks.Use bind variable notation:
select :app_user from dualThis is a reduced example, right? Can't see any reason to run such a query instead of using one of the documented methods of referencing built-in substitution values.
Please try to use the documentation to answer such basic questions. -
Query to find the class name that has the maximum number of students ?
I need the query to find the [class Name] which has the most number of students. please look below at the tables
Students Table
StudentId StudentName ClassID
1 xxx 1
2 yyy 1
3 zzz 1
4 fff 2
5 ttt 2
Classes Table
ClassID ClassNane
1 CSHARP
2 JSHARP
The result should be : CSHARP
since there are 3 students in CSHARP and 2 students in JSHARP class
Appreciate your help
ThanksTry:
DECLARE @Classes TABLE (
ClassID INT identity(1, 1) PRIMARY KEY
,ClassName VARCHAR(50)
INSERT INTO @Classes (ClassName)
VALUES ('CSharp')
,('JSharp')
DECLARE @Students TABLE (
StudentID INT identity(1, 1) PRIMARY KEY
,StudentName VARCHAR(10)
,ClassID INT
INSERT INTO @Students (
StudentName
,ClassID
VALUES (
'xxx'
,1
'yyy'
,1
'zzz'
,1
'fff'
,2
'ttt'
,2
SELECT TOP (1)
WITH TIES C.ClassName
FROM @Classes C
INNER JOIN @Students S ON C.ClassID = S.ClassID
GROUP BY C.ClassID
,C.ClassName
ORDER BY COUNT(S.StudentID) DESC
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
SQL query to find sqlnet.ora parameters
Hi All,
I am working 11g RAC /solaris 9
I want have sql query to find values of sqlnet.ora parameters
May be values of SQLNET.INBOUND_CONNECT_TIMEOUT
SQLNET.SEND_TIMEOUT, SQLNET.RECV_TIMEOUT
Thanks
rajThe sqlnet.ora file is the profile configuration file. It resides on the client machines and the database server.
Profiles are stored and implemented using this file. The database server can be configured with access control parameters in the sqlnet.ora file.
These parameters specify whether clients are allowed or denied access based on the protocol.
The sqlnet.ora file enables you to do the following:
Specify the client domain to append to unqualified names
Prioritize naming methods
Enable logging and tracing features
Route connections through specific processes
Configure parameters for external naming
Configure Oracle Advanced Security
Use protocol-specific parameters to restrict access to the database
By default, the sqlnet.ora file is located in the ORACLE_HOME/network/admin directory. The sqlnet.ora file can also be stored in the directory specified by the TNS_ADMIN environment variable.
You can not query on this file sqlnet.ora as tnsnames.ora file.
Regards
Mahir M. Quluzade -
Query to find Memory used by each session in the database
Hi All,
Is there any query to find the memory utilised by each session in the database.I am in 9i database.
Regards
VijayMemory using sessions script,
SET LINESIZE 145
SET PAGESIZE 9999
COLUMN sid FORMAT 99999 HEADING 'SID'
COLUMN serial_id FORMAT 999999 HEADING 'Serial#'
COLUMN session_status FORMAT a9 HEADING 'Status' JUSTIFY right
COLUMN oracle_username FORMAT a12 HEADING 'Oracle User' JUSTIFY right
COLUMN os_username FORMAT a9 HEADING 'O/S User' JUSTIFY right
COLUMN os_pid FORMAT 9999999 HEADING 'O/S PID' JUSTIFY right
COLUMN session_program FORMAT a18 HEADING 'Session Program' TRUNC
COLUMN session_machine FORMAT a8 HEADING 'Machine' JUSTIFY right TRUNC
COLUMN session_pga_memory FORMAT 9,999,999,999 HEADING 'PGA Memory'
COLUMN session_pga_memory_max FORMAT 9,999,999,999 HEADING 'PGA Memory Max'
COLUMN session_uga_memory FORMAT 9,999,999,999 HEADING 'UGA Memory'
COLUMN session_uga_memory_max FORMAT 9,999,999,999 HEADING 'UGA Memory MAX'
prompt
prompt ----------------------------------------------------
prompt | User Sessions Ordered by Current PGA Size |
prompt ----------------------------------------------------
SELECT
s.sid sid
, s.serial# serial_id
, lpad(s.status,9) session_status
, lpad(s.username,12) oracle_username
, lpad(s.osuser,9) os_username
, lpad(p.spid,7) os_pid
, s.program session_program
, lpad(s.machine,8) session_machine
, sstat1.value session_pga_memory
, sstat2.value session_pga_memory_max
, sstat3.value session_uga_memory
, sstat4.value session_uga_memory_max
FROM
v$process p
, v$session s
, v$sesstat sstat1
, v$sesstat sstat2
, v$sesstat sstat3
, v$sesstat sstat4
, v$statname statname1
, v$statname statname2
, v$statname statname3
, v$statname statname4
WHERE
p.addr (+) = s.paddr
AND s.sid = sstat1.sid
AND s.sid = sstat2.sid
AND s.sid = sstat3.sid
AND s.sid = sstat4.sid
AND statname1.statistic# = sstat1.statistic#
AND statname2.statistic# = sstat2.statistic#
AND statname3.statistic# = sstat3.statistic#
AND statname4.statistic# = sstat4.statistic#
AND statname1.name = 'session pga memory'
AND statname2.name = 'session pga memory max'
AND statname3.name = 'session uga memory'
AND statname4.name = 'session uga memory max'
ORDER BY session_pga_memory DESC
Thanks
Maybe you are looking for
-
IMovie Text and Presets Not Working?
iMovie 11 isn't working properly. The text(Titles) shows up fine on preview but once you're out of the editing thing it shows the text plus random black backgrounds on it. Also, with some of the presets (the animated clips in iMovie) won't work prope
-
MagSafe flashing green/amber
My macbook pro 13" 2011 was working fine all day. I left it for a bit and opened it up at the end of the day and it shut down as soon as the display booted up. I figured it just needed to charge and left it plugged in over night, but there was no cha
-
Any way to get rid of the status bar?
hey there, i use safari 3.0.4 on my 10.4.11 macbook, and i know it's nothing really, but it bugs me from an aesthetical point of view.. i don't have the status showing ever, but sometimes when i click a link and a new window opens, the status bar wil
-
Is it possible to play iTunes audio out through USB to receiver to power speakers?
I thought you should be able to.Play iTunes audio out through USB to a receiver equipt with USB mode as I can with my iPad Air, but I can,t find in preferences on my 2013 iMac any out put and I get no signal to the receiver/amp. Is it possible? What
-
Asset Balances not tally to GL Balances with small difference .1 paisa
Hi Guru, Asset balance report- s_alr_87011964 not tally to GL balance- FBL3N with a small difference .1 paisa,Please sombody can help me solve this issue. Advance thanks. Thanks, ND