Sql query : sum of feild between two conditional date
hi
I have a table whit 3 field like below. I want to Find the
total number of hours in mode "run" after the latest mode "decoke".
field time is for every day and its unique.
id -- time -- mode -- hour
1 --1/1/1 -- run -- 24
2 -- 1/1/2 -- off -- 24
3 -- 1/1/3 decoke -- 24
4 -- 1/1/4 -- run -- 24
5 -- 1/1/5 -- run -- 24
this query should add row 4 and 5 , the latest "run" after "decoke"
Create table #temp
[id] int identity(1,1)
, [time] date
, [mode] varchar(50)
, [hour] int
Insert into #temp
Select '1/1/1' , 'run' ,24
Union
Select '1/1/2' , 'off' ,24
Union
Select '1/1/3' , 'decoke' ,24
Union
Select '1/1/4' , 'run' ,24
Union
Select '1/1/5' , 'run' ,24
-----Here is the Query-------
;With Cte_TotalTime
As
Select Max(time)[Time] from #temp Where mode = 'decoke'
Select SUM(a.hour) TotalRunHours from #temp a
Inner join Cte_TotalTime b on a.[time] > b.[Time]
And mode = 'run'
Drop table #temp
Please mark as answer if it is helpful to you.
Thanks
Similar Messages
-
Execution time of sql query differing a lot between two computer
hi
execution time of a query in my computer and more than 30 different computer is less than one second but on one of our
customers' computers, execution time is more than ten minute. databases and data and queries are same. i re-install sql but problem remains. my sql is ms sql 2008 r2.
any one has idea for this problem?Hi mahdi,
Obviously, we can't get enough information to help you troubleshoot this issue. So, please elaborate your issue with more detail so that the community members can help you in more effecient manner.
In addition, here is a good article regarding checklist for analyzing Slow-Running queries. Please see:
http://technet.microsoft.com/en-us/library/ms177500(v=sql.105).aspx
And SQL Server Profiler and Performance Monitor are good tools to troubleshoot performance issue, please see:
Correlating SQL Server Profiler with Performance Monitor:
https://www.simple-talk.com/sql/database-administration/correlating-sql-server-profiler-with-performance-monitor/
Regards,
Elvis Long
TechNet Community Support -
SQL - Can u print all the dates between two given dates (Without PL/SQL)
Hi Friends,
I want to know if u can print all the dates between two given dates without using pl/sql.
date1,date2 are given
write a sql statement to display all the dates lying between those two dates.
An earlier will be appreciated.
Thanks in Advance
Sriram
nullSriram,
Try this....
select to_date('01-JAN-00')+to_number(rownum)
from all_tables
where rownum < to_date('10-JAN-00')-to_date('01-JAN-00')
TO_DATE('
02-JAN-00
03-JAN-00
04-JAN-00
05-JAN-00
06-JAN-00
07-JAN-00
08-JAN-00
09-JAN-00 -
Query to search between two specific dates and time period
Hi,
Need a query to search between two particular dates and time period
Like i want to search table having one date field .
Suppose the date range is '01-JUL-06' and '01-AUG-06' and time frame
is 23:00:00 to 08:00:00
i.e i want to search between dates 01 july to 01 aug and also within the time frame i.e 23:00 to 08:00 hrs onlyThe general principle is
SELECT * FROM your_table
WHERE some_date BEWTEEN to_date('01-JUL-06') and to_date('01-AUG-06' )+0.99999
AND ( some_date <= trunc(some_date)+8/24
OR some_date >= trunc(some_date)+23/24 )
/Cheers, APC -
How to find particular date lies in between two given dates
hi,
i have a problem. i have to find if particular day lies in between two given dates.
example two dates are joindate and expirydate.
1.joindate is 1/03/2007
expdate is 1/03/2008
now i have to find if 29 feb is in between this joindate and expirydate.
if any1 has ny idea please reply asap.
thanks.The Date class has a before() and after() method you can use to compare Date objects.
-
Hi,
I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work
(fault number -2147217900)
I want to search for a value in a ms access table , if it exist i want to update it, if not i want to insert a new row.
Working with LabView 7.1, database con. toolset.
Who can HELP?
Thanks a lot
MarcoHello,
I think that If exist is not a standar SQL command (I know it exists I think in Oracle and SQL server), MS access doesn't support it, so I think the best way to do it is first make a Select and then either an Update or an insert, sorry...
Paulo -
Download to excel between two given dates
Hi All,
I already implemented Export to Excel funtionality in webdynpro java. Now i have a requirement to download the data to Excel only between two given dates.
I am taking two dates from the user and based on that it should download data into excel file.
Guide me on this or send pseudocode for this.
Regards,
DhruvHi,
If I understand your question correctly,
you are gettting some data from R/3. You need to filter out that data which is in between two given dates , export that data to excel.
If yes, then take one more ValueNode with same structure.
and bind the filtered data to this node.
To filter out model node, use
int size=wdContext.node<outputnode>().size();
Date stDate=wdContext.currentContextElement().get<startDate>();
Date endDate=wdContext.currentContextElement().get<endDate>();
for(int i=0;i<size;i++)
Date objDate=wdContext.node<outputNode>().get<outputNode>ElementAt(i).get<dateAttribute>();
if( (objDate.compareTo(stDate)>=0) && (objDate.compareTo(endDate)<=0) )
// Create element for value Node , set the values (ie. i'th record values) and add to ValueNode.
Long process, but you can use
Now export the ValueNode to excel
Regards
LN
Edited by: Lakshmi Narayana Chowdary Namala on Sep 22, 2008 12:04 PM -
All Dates between two given Dates
Hi,
I need all the dates between two given dates in select-options .
For example the range in select-options is 01/01/2007 - 31/03/2007 .
I need all the dates between the two given dates .
How can i do this .Is there any FM for this ?
Regards,
Ziause this
CSCP_PARA1_GET_PERIODS
data:begin of daytab occurs 0.
include structure scscp_period_str.
data:end of daytab.
call function 'CSCP_PARA1_GET_PERIODS'
exporting
i_datuv = r_budat-low
i_datub = r_budat-high
i_timeunit = 'D'
tables
et_dates = daytab.
here u have to put one more logic.
loop at daytab where datuv in r_budat.
endloop.
So u will get all the dates
Regards
prabhu -
I just wanted to note this on the forum..
I'm using Apex 3.0.1.00.08
My DEV environment has just been upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
I created the following process to select some values into some items on my Form page.
select MAX(STAT_YEAR+1)
, pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id
into :P11_STAT_YEAR
, :P11_PCT_ID
, :P11_STAT_TYPE_ID
, :P11_STAT_PERIOD_TYPE_ID
, :P11_MEASUREMENT_ID
from plant_commodity_data pcd
, stat_type stt
where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
and pcd.pct_id = :P0_PCT_ID
and stt.stat_type = 'PRD'
group by pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id;The process should run conditionally if there was at least one row to select...
So I copied the SQL into the Process condition, removed the "into" section and set the condition type to be "Exists (SQL query retruns at least one row) ...
select MAX(STAT_YEAR+1)
, pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id
from plant_commodity_data pcd
, stat_type stt
where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
and pcd.pct_id = :P0_PCT_ID
and stt.stat_type = 'PRD'
group by pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id;This worked perfectly until the DEV environment was upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
The condition would fire even if there were no rows returning.
I pasted the condition code into SQL Developer connected to the DEV (10.2.0.4.0) environment and it returned no rows.
To solve the problem, I removed the MAX.
You can test this using this code if you have access to the two versions... select MAX(1)
, sysdate
, 'Gus'
from dual
where 1 = 2
group by sysdate, 2Now I know the MAX isn't required in the condition as I'm just trying to find out if any rows exist, but it was there as I copied the code in... I was just wondering why this happened between 10.2.0.2.0 and 10.2.0.4.0?
Gus..Hi Gus,
try to execute
select count(*) from dual where exists (select MAX(1)
, sysdate
, 'Gus'
from dual
where 1 = 2
group by sysdate, 2)in SQL Developer. The above statement is generated by APEX for an "Exists (SQL query retruns at least one row)". Can't test it, because I don't have a 10.2.0.4.0 at hand.
Does SQL Developer now show the same behavior?
Patrick
My APEX Blog: http://www.inside-oracle-apex.com
The APEX Builder Plugin: http://builderplugin.oracleapex.info/
The ApexLib Framework: http://apexlib.sourceforge.net/ -
Hi all,
I think I'm being really stupid but I'm having SQL query issues.
I have a table with lots of lines of transactions which all refer to different stores, for example:
Store..............._Sales_............._Month_
Reading............200k..............April
Leeds...............50k................April
Manchester........70k................May
Reading............100k..............May
I need to come up with the average Sales for the combined months as a total. I.e. the average Store revenue for a given period is 200k+ 50k + 70k +100k / *3* (As there are only 3 unique stores) - hopefully this makes sense!
So essentially I am trying to do both a SUM query (and grouping by store) and then outputting the average of all stores together. Is this possible?
Thank you,Hello,
This query returns 140 what seems to be the correct value:
with data as
( select 'Reading' Store
, 200 sales
from dual
union
select 'Leeds'
, 50
from dual
union
select 'Manchester'
, 70
from dual
union
select 'Reading'
, 100
from dual
select sum(sales)
, count( distinct store )
, sum(sales)/count(distinct store)
from dataThere are multiple options:
1. You can get two IR's on one page (by using IFRAMEs - search for that word on the Forum)....
2. You create another region with the query above and position that just below the report
3. In the Region Footer call a PL/SQL process (using AJAX) that calculates the value using the query and prints it there (using htp.p)
Greetings,
Roel
http://roelhartman.blogspot.com/
http://www.bloggingaboutoracle.org/
http://www.logica.com/
You can award this reply to your question by marking it as either Helpful or Correct ;-) -
Using pl/sql function for each day between two dates.
Hi,
create TABLE EMP(
ID_EMP NUMBER,
DT_FROM DATE,
DT_TO DATE,
CREATE_DATE DATE);
into EMP(ID_EMP, DT_FROM, DT_TO, CREATE_DATE)
Values(100, TO_DATE('07/01/2008 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), TO_DATE('04/30/2010 00:00:00', 'MM/DD/YYYY HH24:MI:SS'),TO_DATE('05/08/2009 14:11:21', 'MM/DD/YYYY HH24:MI:SS'));
I have a function called elig_pay_dates(date p_date), which returns the code for person payment eligibility for a particular date. For paid dates it's 'P' and for unpaid dates it's 'N'.
How can I check this function between two dates for each day. Example : 07/01/2008 to 04/30/2010.
By using this function with select I needs to display the dates when there is a change in status.
I am expecting data in following manner from above logic(this is example):
07/01/2008 --- 07/01/2009 ---'P'
07/02/2009 -- 07/25/2009 ----'N'
07/26/2009 -- 01/01/2010 ---'P'
01/02/2010 -- 01/13/2010 --'N'
01/14/2010 -- 01/18/2010 --'P'
01/19/2010 -- 04/30/2010 -- 'N'
I thought of looping for each day date but that seems to be expensive for online application. Is there any way that I can achieve this requirement with sql query ?
Thanks for your help,Certainly not the best way to code the requirement, but it does achieve the result you are looking for in a fairly quick time
create or replace
function test_ret_paid_unpaid (p_date in date)
return varchar2
is
v_ret varchar2(1);
begin
if ( (p_date between to_date('07/02/2009', 'MM/DD/YYYY') and to_date('07/25/2009', 'MM/DD/YYYY') ) or
(p_date between to_date('01/02/2010', 'MM/DD/YYYY') and to_date('01/13/2010', 'MM/DD/YYYY') ) or
(p_date between to_date('01/19/2010', 'MM/DD/YYYY') and to_date('04/30/2010', 'MM/DD/YYYY') )
then v_ret := 'N';
else
v_ret := 'Y';
end if;
return v_ret;
end;
Wrote file afiedt.buf
1 with get_paid_unpaid as
2 (
3 select dt_from start_date, dt_to end_date, dt_from + level - 1 curr_date, test_ret_paid_unpaid(dt_from + level - 1) paid_unpaid,
4 row_number() over (order by dt_from + level - 1) rn_start,
5 row_number() over (order by dt_from + level - 1 desc) rn_end
6 from test_emp
7 connect by level <= dt_to - dt_from + 1
8 ),
9 get_stop_date as
10 (
11 select start_date init_date, end_date, curr_date, paid_unpaid,
12 case when paid_unpaid != lag(paid_unpaid) over (order by curr_date) or rn_start = 1 or rn_end = 1
13 then curr_date
14 else null
15 end start_date,
16 case when paid_unpaid != lead(paid_unpaid) over (order by curr_date) or rn_start = 1 or rn_end = 1
17 then curr_date
18 else null
19 end stop_date
20 from get_paid_unpaid
21 )
22 select period, paid_unpaid
23 from (
24 select init_date, curr_date, start_date, end_date, stop_date,
25 case when paid_unpaid = lead(paid_unpaid) over (order by curr_date)
26 then nvl(start_date, init_date) || ' - ' || lead(stop_date, 1, end_date) over (order by curr_date)
27 else null
28 end period,
29 paid_unpaid
30 from get_stop_date
31 where stop_date is not null or start_date is not null
32 )
33* where period is not null
12:06:10 SQL> /
PERIOD PAID_UNPAID
01-JUL-08 - 01-JUL-09 Y
02-JUL-09 - 25-JUL-09 N
26-JUL-09 - 01-JAN-10 Y
02-JAN-10 - 13-JAN-10 N
14-JAN-10 - 18-JAN-10 Y
19-JAN-10 - 30-APR-10 N
6 rows selected.
Elapsed: 00:00:00.35 -
SQL Query results to CSV as two worksheets
I'm trying to take two SQL queries and get the results sent to a CSV file on two worksheets. Looking online I have not found a solid example of using the Excel ComObject to create a CSV then add a new worksheet to the CSV file. An added bonus
would be using AutoFit on the columns so everything is easily visible.
Code found online got me the following script which does work, however it takes 12 minutes to pipe the SQL queries to Excel. Switching to a CSV and the script executes in 5 seconds.
This is another nice to have, I was also looking the best way to look at the results (only 1 column) and depending on the length of the data, insert what Excel would call a Cell thereby shifting cells RIGHT but so far have found no clear examples of how
to accomplish that. My guess would be modifying my SQL queries but I've posted a question on StackOverFlow and someone suggested modifying the PowerShell Table created from the SQL dataset.Tables
Code:
$docs = "C:\Scripts\Output.xlsx"
If (Test-Path $docs){Remove-Item $docs}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames)
## - Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application
$xlsObj.DisplayAlerts = $false
$xlsWb = $xlsobj.Workbooks.Add(1)
## - Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0
$time = 2
for ($i = 0; $i -lt $queries.Count; $i++){
$percentage = $i / $time
$remaining = New-TimeSpan -Seconds ($time - $i)
$message = "{0:p0} complete" -f $percentage, $remaining
Write-Progress -Activity "Creating Daily Reboot Spreadsheet" -status $message -PercentComplete ($percentage * 100)
$query = $queries[$i]
$sheetname = $sheetnames[$i]
$xlsSh = $xlsWb.Worksheets.Add([System.Reflection.Missing]::Value, $xlsWb.Worksheets.Item($xlsWb.Worksheets.Count))
$xlsSh.Name = $sheetname
### SQL query results sent to Excel
$SQLServer = 'ServerName'
$Database = 'DataBase'
## - Connect to SQL Server using non-SMO class 'System.Data':
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $query
$SqlCmd.Connection = $SqlConnection
## - Extract and build the SQL data object '$Table2':
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$Table1 = $DataSet.Tables["Table"]
## - Build the Excel column heading:
[Array] $getColumnNames = $Table1.Columns | SELECT ColumnName
## - Build column header:
[Int] $RowHeader = 1
foreach ($ColH in $getColumnNames)
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName
$RowHeader++
## - Adding the data start in row 2 column 1:
[Int] $rowData = 2
[Int] $colData = 1
foreach ($rec in $Table1.Rows)
foreach ($Coln in $getColumnNames)
## - Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@"
## - Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString()
$ColData++
$rowData++; $ColData = 1
## - Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange
[void] $xlsRng.EntireColumn.AutoFit()
}#End For loop.
#Delete unwanted Sheet1.
$xlsWb.Sheets.Item('Sheet1').Delete()
#Set Monday to Active Sheet upon opening Workbook.
$xlsWb.Sheets.Item('Cert').Activate()
## ---------- Saving file and Terminating Excel Application ---------- ##
$xlsFile = "C:\Scripts\Output.xlsx"
[void] $xlsObj.ActiveWorkbook.SaveAs($xlsFile)
$xlsObj.Quit()
## - End of Script - ##
start-sleep 2
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsSh)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsWb)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsObj)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End Function
$queries = @()
$queries += "Query1"
$queries += "Query2"
$sheetnames = @('Cert','Prod')
Run-Query -queries $queries -sheetnames $sheetnamesHere's what I ended up with that accomplishes my goal. I learned it's not possible to create a CSV with two worksheets since Excel will allow this but the CSV cannot be saved with the second worksheet. Instead, I create two CSV files then merge
them into one Excel workbook, one CSV per worksheet. In my case, this happens in 5 seconds. There is one thing which must be mentioned, I've seen this script fail the first time it is run but will successfully run the second time.
Also note, after much trial and error, this code correctly cleans up the Excel ComObject!! -Thanks go to JRV.
$docs = "D:\Scripts\MonthlyReboots.xlsx"
IF (Test-Path $docs){Remove-Item $docs}
$csv1 = "D:\Scripts\Cert.csv"
IF (Test-Path $csv1){Remove-Item $csv1}
$csv2 = "D:\Scripts\Prod.csv"
IF (Test-Path $csv2){Remove-Item $csv2}
Function Run-Query {
param([string[]]$queries,[string[]]$sheetnames,[string[]]$filenames)
Begin{
$SQLServer = 'ServerName'
$Database = 'DataBase'
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = 0
$dest = $Excel.Workbooks.Add(1)
}#End Begin
Process{
For($i = 0; $i -lt $queries.Count; $i++){
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $queries[$i]
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "D:\Scripts\$($sheetnames[$i]).csv" -Force
}#end for loop.
}#End Process
End{
$SqlConnection.Close()
#Excel magic test!
For($i = 0; $i -lt $queries.Count; $i++){
$loopy = (Resolve-Path -Path $filenames[$i]).ProviderPath
$Book = $Excel.Workbooks.Open($loopy)
$next = $Excel.workbooks.Open($loopy)
$next.ActiveSheet.Move($dest.ActiveSheet)
$xlsRng = $dest.ActiveSheet.UsedRange
$xlsRng.EntireColumn.AutoFit() | Out-Null
$dest.sheets.item('Sheet1').Delete()
$xlsFile = "D:\Scripts\MonthlyReboots.xlsx"
[void] $Excel.ActiveWorkbook.SaveAs($xlsFile)
$Excel.Quit()
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xlsRng)) {'cleanup xlsRng'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($next)) {'cleanup xlsSh'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Book)) {'cleanup xlsWb'}
While ([System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)) {'cleanup xlsObj'}
[gc]::collect() | Out-Null
[gc]::WaitForPendingFinalizers() | Out-Null
}#End end block.
}#End function run-query.
$queries = @()
$queries += @'
Select * from table1
$queries += @'
Select * from table2
$sheetnames = @("Cert","Prod")
$filenames = @("D:\Scripts\Prod.csv","D:\Scripts\Cert.csv")
Run-Query -queries $queries -sheetnames $sheetnames -filenames $filenames
Start-Sleep -Milliseconds 50
Invoke-Item D:\Scripts\MonthlyReboots.xlsx -
Hello,
I've set up a region definition of type "SQL Query(PL/SQL function body return SQL query). In my query I make use of an "in" condition. When I populate :P755_INC_BARG_UNIT with a value of 0F (no quotes), I get the correct count. However, when I set :P755_INC_BARG_UNIT to 0F, 0E I get an invalid count. What do I have to set the page item to?
When running the query in TOAD, and setting :P755_INC_BARG_UNIT to the string inside the brackets (0F, 0E) I get the proper count.
The code I use is shown below. Any help would be appreciated,
Alex.
DECLARE
v_sql VARCHAR2(32767);
BEGIN
SELECT count(*) "cnts",
''Faculty data file IDs missing in appt table'' "err_type"
FROM hradmin.et_faculty_salary fs left outer join
hradmin.appointments appt
ON trim(fs.empl_id) = appt.emp_emp
and appt.ear_activ <> ''Z''
and appt.ear_type = ''F''
and (appt.ear_class in (''A'',''B'',''C'',''D''))
and appt.ear_bargunit in ( :P755_INC_BARG_UNIT )
WHERE appt.emp_emp is null
RETURN v_sql;
END;Alex,
try something like:
DECLARE
v_sql VARCHAR2(32767);
BEGIN
v_sql := <YOUR_SQL_STATEMENT_WITH_P755_INC_BARG_UNIT_IN_IT>;
v_sql := REPLACE(v_sql, ':P755_INC_BARG_UNIT',:P755_INC_BARG_UNIT);
RETURN v_sql;
END; But before doing it read this:
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:210612357425
After reading you will be able to find the best solution yourself.
Lev -
Sql query question - been trying for two days
Hi guys im trying to carry out an sql query
Im using a left join to do a query, which gives me a set of results:
select COURSESTUDENT.StudentNo, COURSESTUDENT.CourseCode, COURSESTUDENT.Year, MARKS.ExamMark, MARKS.EntryNo FROM COURSESTUDENT LEFT JOIN MARKS ON COURSESTUDENT.StudentNo=MARKS.StudentNo AND COURSESTUDENT.CourseCode=MARKS.CourseCode AND COURSESTUDENT.Year=MARKS.Year
but I would like to do a select on this result but do not want to use a create view as if more than one person access this page at a time then if the servlet tries to create the view an error will occur.
I would like to do the following select statement on the results of the query above..
select * from (above) where CourseCode='ELE304' AND Year=1999;
Is this possible, im using postgres..
Please help......
thanks
tzafSorry, I have never used postgres, but in several databases, the following syntax would work and provide the correct ResultSet.
select *
from (
SELECT
COURSESTUDENT.StudentNo,
COURSESTUDENT.CourseCode,
COURSESTUDENT.Year,
MARKS.ExamMark,
MARKS.EntryNo
FROM
COURSESTUDENT LEFT JOIN MARKS ON
COURSESTUDENT.StudentNo=MARKS.StudentNo AND
COURSESTUDENT.CourseCode=MARKS.CourseCode AND
COURSESTUDENT.Year=MARKS.Year
) A
WHERE
CourseCode='ELE304' AND
Year=1999 -
Sql query to find activities between Login and Logout time
Hi ,
I have 2 tables as shown below
User Table
ActivityTable
i have a requirement in which i need to find all the activities done for a particular user inbetween login and logout time can anybody help me how to write sql query for this .Is this what you looking for?
DECLARE @User TABLE
userid INT,
date DATETIME,
type VARCHAR(50),
sessionid SMALLINT
DECLARE @ActivityTable TABLE
activityid SMALLINT,
userid SMALLINT,
activity VARCHAR(50),
activitystarttime DATETIME,
activityendtime DATETIME
INSERT INTO @User
(userid,
[date],
[type],
sessionid)
VALUES (1,
'2002-08-25 16:51:25.107',
'Logon',
111),
(1,
'2002-08-25 17:52:25.107',
'LOGOFF',
111),
(2,
'2007-03-08 19:25:21.170',
'Logon',
222),
(2,
'2007-03-08 21:25:21.170',
'LOGOFF',
222),
(3,
'2007-03-08 19:25:21.170',
'Logon',
234);
INSERT INTO @ActivityTable
(activityid,
userid,
activity,
activitystarttime,
activityendtime)
VALUES (234,
1,
'development',
'2002-08-25 16:53:23.101',
'2002-08-25 16:59:23.170'),
(789,
2,
'Testing',
'2007-03-08 19:53:23.180',
'2007-03-08 20:53:23.180'),
(789,
2,
'Lunch',
'2007-03-08 19:53:23.180',
'2007-03-08 20:53:23.180'),
(456,
3,
'Testing',
'2007-03-08 19:53:23.180',
'2007-03-08 20:53:23.180'),
(781,
1,
'Lunch',
'2002-08-25 17:00:23.101',
'2002-08-25 17:30:00.170'),
(781,
1,
'Lunch',
'2002-08-25 21:00:23.101',
'2002-08-25 22:30:00.170');
WITH logon
AS (SELECT date,
userid
FROM @User
WHERE type = 'Logon'),
logoff
AS (SELECT date,
userid
FROM @User
WHERE type = 'LOGOFF')
SELECT at.*
FROM @ActivityTable AT
INNER JOIN logon Lo
ON at.userid = lo.userid
INNER JOIN logoff LF
ON at.userid = lf.userid
WHERE At.activityendtime < LF.date
AND AT.activitystarttime > LO.date
Regards,
Vishal Patel
Blog: http://vspatel.co.uk
Site: http://lehrity.com
Maybe you are looking for
-
How to create a view in table DB for a few servers
Hi We need to create a table Country that will hold the countries data. I would like to create it in a way that it will be common for all the servers - but as a view. not the real table, only a view to see the data and not to change it. How do I do i
-
Portable Home Directory no longer works on Lion bound to Active DirectoryAD
Hi, All, I look after about 30 MacBook Air/Pro connected to a predominantly Windows corporate network. A few months back, I installed a MacOS Server running OpenDirectory and Software Update Services for managing the MacBooks - they are configured in
-
Elements 13 disc problem installation
Hi, I have trialled free Elements 13 (which is still valid for 2-3 weeks) and decided to buy the disc version. It does not install or give out any message at all regards the problem.The disc is heard revolving inside. Contacted Store where I bought
-
Prints in color even when I check B&W only
Finally upgraded to Snow Leopard and now my Canon Pixma IP4300 only prints in color even when I check B&W only.
-
Reg: Tracking the sales order no in the Purchase requsition or in the PO
Hi All, i need some information on the sales order related issue. actually i have create the prchase requsition against the sales order and also i have convert this PR to PO order. but i want to see my sales order number in the PR or PO. how can i se