Simpler reprsentation to SQL Query is needed
Hi all,
I have this SQL Query working goon on the Database but have some errors with Form developer so can anybody simplify it?
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM Returned_Goods
JOIN Products
ON returned_goods.productId = products.Id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1;btw, the error encounter me in Forms appears here if anybody can help: [SQL Code not working in Forms Developer without Functions|http://forums.oracle.com/forums/thread.jspa?threadID=842122&tstart=0]
Thanks in advance :)
The simpler SQL Staement is
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM returned_goods, products
WHERE
Returned_Goods.ProductId = Products.id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1;
Similar Messages
-
I'm having trouble with an SQL query. I've created a simple logon page wherein a user will enter their user name and password. The program will look in an Access database for the user name, sort it by Date/Time modified, and check to see if their password matches the most recent password. Unfortunately, the query returns no results. I'm absolutely certain that I'm doing the query correctly (I've imported it directly from my old VB6 code). Something simple is eluding me. Any help would be appreciated.
private void LogOn() {
//make sure that the user name/password is valid, then load the main menu
try {
//open the database connection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:LawOffice2000", "", "");
Statement select = con.createStatement();
String strTemp = "Select * From EMPLOYEES Where INITIALS = '" + txtUserName.getText() + "' Order By DATE Desc, TIME Desc";
ResultSet result = select.executeQuery(strTemp);
while(result.next()) {
if (txtPassword.getPassword().toString() == result.getString("Password")) {
MenuMain.main();
else {
System.out.println("Password Bad");
System.out.println(txtUserName.getText());
System.out.println(result.getString("Password"));
break; //exit loop
//close the connection
con.close(); }
catch (Exception e) {
System.out.println("LawOfficeSuite_LogOn: " + e);
return; }
}The problem is here: "txtPassword.getPassword().toString() == result.getString("Password"))"
Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same characters), use equals(), e.g. if (str1.equals(str2))...
Example:String s1 = "foo";
String s2 = new String("foo");
System.out.println("s1 == s2: " + (s1 == s2)); // false
System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus == -
What SQL query I need for this?
I need to execute a SQL query but I don't know how.
To illustrate it, please take a look at some example data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31
1 2004-12-31
1 2004-11-31
2 2005-12-31
2 2005-11-31
2 2005-10-31
2 2005-09-31 This is a piece of the sales data for the articles (sales history).
Lets assume that today is the date 2005-12-31.
Two requirements for the query:
1. Get the sales data for the last 12 months.
2. Get only the sales data for articles where there is sales data since at least 6 months.
The result in my example should look like this:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31 What is the SQL which I need to accomplish this query?To get all the information from the last 12 months
you will have to use date manipulation.
SELECT add_months(sysdate, -12) from
dual;This gives you the date 12 months ago.
So you will have to select your date between then and
the current date.If I do this I will get this data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31
2 2005-12-31
2 2005-11-31
2 2005-10-31
2 2005-09-31 But I want this data:
ARTICLEID SOLDON
1 2005-12-31
1 2005-11-31
1 2005-10-31
1 2005-09-31
1 2005-08-31
1 2005-07-31
1 2005-06-31
1 2005-05-31
1 2005-04-31
1 2005-03-31
1 2005-02-31
1 2005-01-31 I am no native English speaker. What didn't you understand in the two requirements?
Here are my two requirements for the query:
1. Get the sales data for the last 12 months.
2. But get ONLY the sales data for articles where there is sales data since AT LEAST 6 months.
The result can contain as many IDs as you want if the two requirements are met. Its not a trivial SQL statement for me. Please remember that the above data are only for illustration. They are just an example.
There should be a SQL statement for this.
Please tell me if you don't understand my problem. I will try to explain it in a better way if I can. -
SQL Query Performance needed.
Hi All,
I am getting performance issue with my below sql query. When I fired it, It is taking 823.438 seconds, but when I ran query in, it is taking 8.578 seconds, and query after in is taking 7.579 seconds.
SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2, BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS, BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
SEG.SEGMENT_DESCRIPTION FROM ACC_SEGMENTS_V_TST SEG , ACC_BALANCE_STG BAL where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE AND SEG.SEGMENT_COLUMN = 'SEGMENT99' AND BAL.ACCOUNTING_PERIOD = 'MAY-10' and BAL.comb_id
in
(select comb_id from
(select comb_id, rownum r from
(select distinct(comb_id),LAST_UPDATE_DATE from ACC_BALANCE_STG where accounting_period='MAY-10' order by LAST_UPDATE_DATE )
where rownum <=100) where r >0)
Please help me in fine tuning above. I am using Oracle 10g database. There are total of 8000 records. Let me know if any other info required.
Thanks in advance.In recent versions of Oracle an EXISTS predicate should produce the same execution plan as the corresponding IN clause.
Follow the advice in the tuning threads as suggested by SomeoneElse.
It looks to me like you could avoid the double pass on ACC_BALANCE_STG by using an analytical function like ROW_NUMBER() and then joining to ACC_SEGMENTS_V_TST SEG, maybe using subquery refactoring to make it look nicer.
e.g. something like (untested)
WITH subq_bal as
((SELECT *
FROM (SELECT BAL.L_ID, BAL.L_TYPE, BAL.L_NAME, BAL.NATURAL_ACCOUNT,
BAL.LOCATION, BAL.PRODUCT, BAL.INTERCOMPANY, BAL.FUTURE1, BAL.FUTURE2,
BAL.CURRENCY, BAL.AMOUNT_PTD, BAL.AMOUNT_YTD, BAL.CREATION_DATE,
BAL.CREATED_BY, BAL.LAST_UPDATE_DATE, BAL.LAST_UPDATED_BY, BAL.STATUS, BAL.ANET_STATUS,
BAL.COG_STATUS, BAL.comb_id, BAL.MESSAGE,
ROW_NUMBER() OVER (ORDER BY LAST_UPDATE_DATE) rn
FROM acc_balance_stg
WHERE accounting_period='MAY-10')
WHERE rn <= 100)
SELECT *
FROM subq_bal bal
, acc_Segments_v_tst seg
where BAL.NATURAL_ACCOUNT = SEG.SEGMENT_VALUE
AND SEG.SEGMENT_COLUMN = 'SEGMENT99';However, the parentheses you use around comb_id make me question what your intention is here in the subquery?
Do you have multiple rows in ACC_BALANCE_STG for the same comb_id and last_update_date?
If so you may want to do a MAX on last_update_date, group by comb_id before doing the analytic restriction.
Edited by: DomBrooks on Jun 16, 2010 5:56 PM -
Sql query ..need idea to write complex query
Hi there,
I have assigned the task to write a sql query to get the output as the below stored proc does.
In the proc conditions are given with IF statements. I really dont know how to give all the conditions for the period in a single sql query as I'm not much used to sql quries.
Is anyone could help me?
Any suggestions pls . writing complicated query is nightmare. no idea . if possible help me...
create or replace PROCEDURE vpp_station_summary_report (
in_user_id IN VARCHAR2,
in_report_id IN NUMBER,
in_time_from IN vppstation.avi_status_history.status_eff_date%TYPE,
in_time_to IN vppstation.avi_status_history.status_eff_date%TYPE,
result OUT SYS_REFCURSOR)
AS
CURSOR station_loop IS
SELECT ash.station_id,
ash.avi_id,
ash.state_id,
ash.state_eff_date
FROM vppstation.avi_state_history ash
JOIN vpproadside.vpp_report_stations
ON vpp_report_stations.station_id = ash.station_id
AND vpp_report_stations.vpp_report_seq_number = in_report_id
WHERE ash.state_eff_date BETWEEN in_time_from AND in_time_to
ORDER BY ash.station_id,
ash.avi_id,
ash.state_eff_date,
ash.ash_id;
-- cursor to find the 'entry state' i.e. the state the AVI was in AT the time of
-- in_time_from
CURSOR entry_state (
state_station_id vppstation.avi_state_history.station_id%TYPE,
state_avi_id vppstation.avi_state_history.avi_id%TYPE,
state_state_date vppstation.avi_state_history.state_eff_date%TYPE
IS
SELECT ash.state_id
FROM vppstation.avi_state_history ash
WHERE ash.station_id = state_station_id
AND ash.avi_id = state_avi_id
AND ash.state_eff_date < state_state_date
ORDER BY ash.state_eff_date DESC,
ash.ash_id DESC;
current_station_id vppstation.avi_state_history.station_id%TYPE;
current_avi_id vppstation.avi_state_history.avi_id%TYPE;
current_state_id vppstation.avi_state_history.state_id%TYPE;
current_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
period_length NUMBER;
next_station_id vppstation.avi_state_history.station_id%TYPE;
next_avi_id vppstation.avi_state_history.avi_id%TYPE;
next_state_id vppstation.avi_state_history.state_id%TYPE;
next_state_eff_date vppstation.avi_state_history.state_eff_date%TYPE;
station_open_total NUMBER;
station_closed_total NUMBER;
station_all_report_total NUMBER;
current_station_name vpproadside.vpp_station_summary.station_name%TYPE;
state_open vppstation.avi_control_state_code.state_id%TYPE;
state_closed vppstation.avi_control_state_code.state_id%TYPE;
state_all_report vppstation.avi_control_state_code.state_id%TYPE;
BEGIN
SELECT state_id
INTO state_open
FROM vppstation.avi_control_state_code
WHERE state_type = 'E'
AND state_active_ind = 'A';
SELECT state_id
INTO state_closed
FROM vppstation.avi_control_state_code
WHERE state_type = 'D'
AND state_active_ind = 'A';
SELECT state_id
INTO state_all_report
FROM vppstation.avi_control_state_code
WHERE state_type = 'S'
AND state_active_ind = 'A';
current_station_id := -1;
current_avi_id := -1;
current_state_id := state_closed;
current_state_eff_date := in_time_from;
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
-- for starters - ensure that there is report data for all requested stations...
INSERT INTO vpproadside.vpp_station_summary
vpp_report_seq_number,
station_id,
station_name,
ln_number,
lane_name,
station_open,
station_close,
station_all_report,
station_total
SELECT in_report_id,
vrs.station_id,
si.station_name,
l.ln_number,
l.lane_name,
0.0,
0.0,
0.0,
0.0
FROM vpproadside.vpp_report_stations vrs
LEFT OUTER JOIN vpproadside.stations_installed si
ON si.station_id = vrs.station_id
LEFT OUTER JOIN vppstation.lane_name l
ON l.station_id = vrs.station_id
WHERE vrs.vpp_report_seq_number = in_report_id;
-- loop over state history and update information for all stations found
OPEN station_loop;
LOOP
FETCH station_loop
INTO
next_station_id,
next_avi_id,
next_state_id,
next_state_eff_date;
IF station_loop%NOTFOUND THEN
next_station_id := -1;
next_avi_id := -1;
END IF;
-- if station/avi has changed take the end of the report period
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
period_length := in_time_to - current_state_eff_date;
ELSE
-- otherwise the start of the next period marks the end of the current period
period_length := next_state_eff_date - current_state_eff_date;
END IF;
-- if we have a real station id then do some work...
IF (current_station_id <> -1) THEN
-- determine which category the period fits to and apply calculation
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length - 1;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length - 1;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length - 1;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
-- if the station/avi has changed then commit changes to db
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
UPDATE vpproadside.vpp_station_summary
SET
station_open = station_open_total,
station_close = station_closed_total,
station_all_report = station_all_report_total
WHERE vpp_report_seq_number = in_report_id
AND station_id = current_station_id
AND ln_number = current_avi_id;
-- reset counts
station_open_total := 0.0;
station_closed_total := 0.0;
station_all_report_total := 0.0;
END IF;
END IF;
-- if we got past the last record then stop processing
EXIT WHEN station_loop%NOTFOUND;
-- if the station/avi is changing, get the state that was 'current' at in_time_from
IF (next_station_id <> current_station_id)
OR (next_avi_id <> current_avi_id)
THEN
current_state_eff_date := in_time_from;
OPEN entry_state (
next_station_id,
next_avi_id,
in_time_from
FETCH entry_state
INTO current_state_id;
IF entry_state%NOTFOUND THEN
current_state_id := state_closed;
END IF;
CLOSE entry_state;
period_length := next_state_eff_date - current_state_eff_date;
IF current_state_id = state_open THEN
station_open_total := station_open_total + period_length;
ELSIF current_state_id = state_closed THEN
station_closed_total := station_closed_total + period_length;
ELSIF current_state_id = state_all_report THEN
station_all_report_total := station_all_report_total + period_length;
ELSE
RAISE_APPLICATION_ERROR(-20111, 'Error: found unknown state code on avi_state_history - ' || current_state_id );
END IF;
END IF;
current_state_id := next_state_id;
current_state_eff_date := next_state_eff_date;
current_station_id := next_station_id;
current_avi_id := next_avi_id;
END LOOP;
CLOSE station_loop;
-- update the totals for the percentage calculation
UPDATE vpproadside.vpp_station_summary
SET
station_total = station_open + station_close+ station_all_report
WHERE vpp_report_seq_number = in_report_id;
-- 'fix' the totals that are still zero to avoid divide by zero errors...
-- note: all the percentages will still come out as zero since the total
-- was zero
UPDATE vpproadside.vpp_station_summary
SET
station_total = 1.0
WHERE vpp_report_seq_number = in_report_id
AND station_total = 0.0;
OPEN result FOR
SELECT station_name "Site Name",
lane_name "Lane Name",
TO_CHAR((station_open / station_total) * 100.0, 'FM990.0999') || '%' "Open %",
TO_CHAR((station_close / station_total) * 100.0, 'FM990.0999') || '%' "Closed %",
TO_CHAR((station_all_report / station_total) * 100.0, 'FM990.0999') || '%' "All Report %"
FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id
ORDER BY UPPER(station_name),
UPPER(lane_name);
DELETE FROM vpproadside.vpp_station_summary
WHERE vpp_report_seq_number = in_report_id;
END;Edited by: Indhu Ram on Mar 10, 2010 9:51 AM
Edited by: Indhu Ram on Mar 10, 2010 9:56 AM
Edited by: Indhu Ram on Mar 10, 2010 10:58 AM
Edited by: Indhu Ram on Mar 10, 2010 11:12 AMExactly dont know what you are asking for but I can suggest you some tips here
- If you want to check the condition in SQL query then you can use CASE statement into select clause i.e.
SELECT CASE when table1.a=table2.b then table1.c else table2.c END, ... more case..., table columns...
FROM table1, table2
WHERE
<some conditions>
- If you want to achive same functionality (SELECT only, not UPDATE/INSERT/DELETE) then you can convert the part of same procedure into function and can use the same function into your query by passing the parameters.
something like this
SELECT function_name(parameter1, parameter2....) from dual
Hope this will help -
UCCX SQL query assistance needed.
Hello,
I am working on a SQL query that does a lookup of the calling number and the last four digits entered by the customer. If I hard code the lastFourGC variable I am able to return a successful result. If I use $lastFourGC I get the following error.
$callingNumber - Is exactly that, the calling number.
$lastFourGC - Is the last four digits collected from the customer.
SELECT * FROM GiftCardFulfillment WHERE Phone=$callingNumber and Right (GiftCard16DigitNumber, 4)=$lastFourGCTanner,
I had tried that with single and double quotes and it didn't work. I did end up getting it to work by rearranging the order. I'm not sure why that worked, but this is what the query looks like now and it works.
SELECT * FROM [leads].[dbo].[GiftCardFulfillment]
WHERE Right (GiftCard16DigitNumber, 4)=$lastFourGC and Phone=$callingNumber -
Simple SQL query..need help
Hi All,
I have a requirement not to show the row, if all columns value is zero. Could someone help me how to do it?
For example:
A B C D E
1 1 5 1 2
1 0 5 0 2
0 9 7 1 0
0 0 0 0 0
From the above example the only last row should not be shown, because all columns value is zero.
Thanks in advance.Another way:
with abc as (select 1 a, 1 b, 5 c, 1 d, 2 e from dual union all
select 1 a, 0 b, 5 c, 0 d, 2 e from dual union all
select 0 a, 9 b, 7 c, 1 d, 0 e from dual union all
select 0 a, 0 b, 0 c, 0 d, 0 e from dual union all
select null a, 0 b, 0 c, 0 d, 0 e from dual)
select a, b, c, d, e
from abc
where (nvl(a, 0), nvl(b, 0), nvl(c, 0), nvl(d, 0), nvl(e, 0)) not in (select 0,0,0,0,0 from dual);
A B C D E
1 1 5 1 2
1 0 5 0 2
0 9 7 1 0 -
Sql query performance need to get improved
hi all..
i got performnace issue with my sp where i used 3 cte's.. i'm posting my code.please help me how can i improve the performance of query
i created non-clustered indexes for tables based on the keys with which the tables are joined..
USE [OPTM]
GO
/****** Object: StoredProcedure [dbo].[GetSample] Script Date: 01/07/2014 10:29:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetSample]
@StartDate DateTime,
@EndDate DateTime,
@Portfolio int,
@Program int,
@Project int
AS
Date Author Purpose
06/11/2012 Ajeesh.C To get the Workitem details for the Scope Workitem Green chart Report.
06/11/2012 Shinoj.P T-SQL re-structuring.
Testing :
exec [dbo].[GetSample] '01/01/2013','12/31/2013',-1,-1,-1
exec [dbo].[GetSample] '01/01/2013','12/31/2013',16,24,199
exec [dbo].[GetSample] '11/01/2013','12/31/2013',-1,-1,703
exec [dbo].[GetSample] '11/01/2012','11/30/2012',8,-1,-1
select * from tb_Portfolio
BEGIN
DECLARE @Scope nvarchar(250),@ScopeID int,@ProjectID int,@WorkItem nvarchar(250),@ProgramID int, @PortfolioID int;
-------Added 3 columns(StatusID,Status,TaskID)--------
CREATE TABLE #GrnChartTempTable
AllocationDate datetime NULL,
Division nvarchar(50) NULL,
DivisionID int NULL,
ResourceName nvarchar(250) NULL,
ResourceEmailID nvarchar(max) NULL,
ResourceID int NULL,
Project nvarchar(250) NULL,
ProjectID int NULL,
Scope nvarchar(MAX) NULL,
ScopeID int NULL,
WorkItem nvarchar(MAX) NULL,
TaskStartDate datetime NULL,
TaskEndDate datetime NULL,
ProgramID int NULL,
Program nvarchar(250) NULL,
PortfolioID int NULL,
Portfolio nvarchar(250) NULL,
StatusID int NULL,
Status nvarchar(50) NULL,
TaskID int null,
EstimateHrs nvarchar(250) NULL,
ScopeEstimateHrs int NULL,
Allocated int NOT NULL
WITH Datematrix(AllocationDate)
As
SELECT @StartDate AS AllocationDate
UNION ALL
SELECT DATEADD(D,1,AllocationDate) AS AllocationDate
FROM Datematrix WHERE AllocationDate<@EndDate
Allocation (Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project
,ProjectID,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs)
AS
SELECT
DIV.Division
,RES.DivisionID
,RES.ResourceName
,ResourceEmailID = STUFF((
SELECT COALESCE( ', ' + CONVERT(VARCHAR,RES.Email1), '')
FROM dbo.TasksResource TSKRES WITH(NOLOCK) LEFT OUTER JOIN
dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
WHERE TSKRES.TaskID = TSK.TaskID
FOR XML PATH('')), 1, 1, '')
,RES.UID ResourceID
,PRJ.Project + ' (' + CONVERT(VARCHAR(15),PRJ.StartDate,101) +' - ' + CONVERT(VARCHAR(15),PRJ.EndDate,101) + ')' as Project
,PRJ.UID ProjectID
,SCP.Title Scope
,SCP.ScopeID
,TSK.Title WorkItem
,TSK.StartDate TaskStartDate
,TSK.EndDate TaskEndDate
,PRJ.ProgramID
,PR.Program
,PR.PortfolioID
,PF.Portfolio
,TSK.StatusID
,ST.Status
,TSK.TaskID
,TSK.EstimateHrs
,(isnull(SCP.EstimateARCH,0) + isnull(SCP.EstimateBA,0) + isnull(SCP.EstimateDev,0) + isnull(SCP.EstimatePM,0) + isnull(SCP.EstimateQA,0) + isnull(SCP.EstimateRM,0)) as ScopeEstimateHrs
--SCP.EstimateARCH + SCP.EstimateBA +SCP.EstimateDev +SCP.EstimatePM +SCP.EstimateQA +SCP.EstimateRM as ScopeEstimateHrs
FROM Tasks TSK WITH(NOLOCK)
INNER JOIN dbo.Scope SCP WITH(NOLOCK) ON TSK.ScopeID = SCP.ScopeID
INNER JOIN dbo.tb_Project PRJ WITH(NOLOCK)ON TSK.ProjectID = PRJ.UID
INNER JOIN dbo.tb_Program PR WITH(NOLOCK) ON PR.UID=PRJ.ProgramID
INNER JOIN dbo.tb_Portfolio PF WITH(NOLOCK)ON PF.UID=PR.PortfolioID
LEFT OUTER JOIN dbo.TasksResource TSKRES WITH(NOLOCK)ON TSKRES.TaskID = TSK.TaskID
LEFT OUTER JOIN dbo.tb_Resource RES WITH(NOLOCK) ON RES.UID = TSKRES.ResourceID
LEFT JOIN dbo.tb_Division DIV WITH(NOLOCK) ON RES.DivisionID = DIV.UID
LEFT JOIN dbo.tb_Status ST WITH(NOLOCK) ON TSK.StatusID=ST.UID /*relating with the high level work items */
WHERE (PRJ.UID = @Project OR @Project = -1)
AND (PRJ.ProgramID = @Program OR @Program = -1)
AND (PRJ.PortfolioID =@Portfolio OR @Portfolio = -1)
MainData (AllocationDate,Division,DivisionID,ResourceName,ResourceEmailID,ResourceID,Project,ProjectID
,Scope,ScopeID,WorkItem,TaskStartDate,TaskEndDate
,ProgramID ,Program,PortfolioID ,Portfolio,StatusID,Status,TaskID,EstimateHrs,ScopeEstimateHrs,Allocated)
AS
( SELECT
Datematrix.*
,Allocation.*
,CASE WHEN ISDATE(TaskStartDate)=1 THEN 1 ELSE 0 END AS Allocated
FROM Datematrix FULL OUTER JOIN Allocation
ON ( Datematrix.AllocationDate>= Allocation.TaskStartDate
AND Datematrix.AllocationDate<=Allocation.TaskEndDate
INSERT INTO #GrnChartTempTable
SELECT * FROM MainData
OPTION (MAXRECURSION 0);
SELECT TOP 1 @Scope=Scope,@ScopeID=ScopeID, @ProjectID=ProjectID
,@WorkItem=WorkItem,@ProgramID=ProgramID,@PortfolioID=PortfolioID
FROM #GrnChartTempTable WHERE Scope IS NOT NULL AND ISDATE(AllocationDate)=1 ORDER BY Scope ;
SELECT AllocationDate,Division,DivisionID
,ResourceName,ResourceEmailID,ResourceID,Project
,ISNULL(ProjectID,@ProjectID) ProjectID
,ISNULL(Scope,@Scope) Scope
,ISNULL(ScopeID,@ScopeID) ScopeID
,ISNULL(WorkItem,@WorkItem) WorkItem
,TaskStartDate,TaskEndDate
,ISNULL(ProgramID ,@ProgramID) ProgramID
,Program
,ISNULL(PortfolioID,@PortfolioID) PortfolioID
,Portfolio,StatusID,Status,TaskID,EstimateHrs,isnull(ScopeEstimateHrs,0)ScopeEstimateHrs,Allocated
FROM #GrnChartTempTable MainData
WHERE ISDATE(MainData.AllocationDate)=1
AND ISNULL(Scope,@Scope) IS NOT NULL
--WHERE FinalData.Scope IS NOT NULL
END
this is my code pls help..
luckyYou need to focus on optimizing your code by looking at the logic and removing any extraneous rows that you do not need - stop depending on the optimizer to do your work.
You have the following in multiple lines: ISDATE(AllocationDate)=1
Look at your final resultset. You do not want any other rows (where isdate() <> 1) so stop selecting them in the first place. In addition, you are using a full outer join in the first query that uses this logic. Since you do not qualify
your columns with the tablename (or alias - which is a best practice), I cannot say if the isdate logic negates the full outer join - but I suspect it might. I also question the logic behind the assignment of the local variables and their use in the
final query. You could remove the separate assignment query (and the variables) by simply moving that query into a derived table (or cte) of the final query. That might not be a significant improvement (you did not give any indications about the size
of the various queries) but I think it is simpler, more resilient, more obvious. I also question the reasoning behind the use of a full outer join.
Why do you left join to dbo.tb_Status? Does not every task have a status?
You join to the TaskResource and tb_Resource tables multiple times (in the Allocation cte) - and it appears that there is a 1/m relationship between task and this joined resultset. Yet the primary query of the Allocation cte does no aggregation.
That is concerning, but I don't know your data so perhaps this is correct. OTH, perhaps it depends on an assumption and your existing data has not yet violated that assumption.
But these are only guesses. As Erland indicates, optimzing requires knowledge of the tables, the data, your business logic, etc. -
Simple Math in SQL Query or cfset
Calculated fields in the DB vs <cfset>?
It would seem simple, but:
ACCESS DB ;>(
CF9
IIS
<cfquery name="get_total" datasource="#Request.BaseDSN#">
SELECT SUM((current_charge+penalty)-credit) AS total
FROM moorings
WHERE mooring_ID = #URL.mooring_ID#
</cfquery>
<cfdump var="#total#">
Variable TOTAL is undefined?
or
<cfset subtotal = current_charge+penalty>
<cfset total = subtotal-credit>
Variable CURRENT_CHARGE is undefined?
Missing ',", (, #'s?
ThanksRun the query without using SUM to see what values are stored in the database:
<cfquery name="get_total" datasource="#Request.BaseDSN#">
SELECT current_charge, penalty, credit
FROM moorings
WHERE mooring_ID = #URL.mooring_ID#
</cfquery>
<cfoutput>
charge: #get_total.current_charge#<br />
penalty: #get_total.penalty#<br />
credit: #get_total.credit#<br />
</cfoutput>
or
<cfdump var="#get_total#">
Also, it's a good idea to get into the habit of using cfqueryparam in your SQL queries. It helps sanitize your inputs and prevents SQL injection attacks:
<cfquery name="get_total" datasource="#Request.BaseDSN#">
SELECT current_charge, penalty, credit
FROM moorings
WHERE mooring_ID = <cfqueryparam value="#URL.mooring_ID#" cfsqltype="cf_sql_integer">
</cfquery> -
Tweak for sql query - help needed for smalll change
Hi.
I am trying to run a script that checks for used space on all tablespaces and returns the results.
So far so good:
set lines 200 pages 2000
col tablespace_name heading 'Tablespace' format a30 truncate
col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
col used_space_mb heading 'MB|Used' format 9G999G999D99
col free_space_mb heading 'MB|Free Till Max' like used_space_mb
col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
col pct_used heading '%|Used' format 999D99
col pct_free heading '%|Free' like pct_used
break on report
compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
select
alloc.tablespace_name,
(alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
free.free_space_mb free_space_ext_mb,
((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
FROM (SELECT tablespace_name,
ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
ROUND(SUM(bytes)/1048576) total_allocspace_mb
FROM dba_data_files
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name) alloc,
(SELECT tablespace_name,
SUM(bytes)/1048576 free_space_mb
FROM dba_free_space
WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
GROUP BY tablespace_name) free
WHERE alloc.tablespace_name = free.tablespace_name (+)
ORDER BY pct_used DESC
The above returns something like this:
MB MB % %
Tablespace Used Free Till Ext Used Free
APPS_TS_ARCHIVE 1,993.13 54.88 97.32 2.68
APPS_TS_TX_IDX 14,756.13 1,086.88 91.37 8.63
APPS_TS_TX_DATA 20,525.75 594.25 80.18 19.82
APPS_TS_MEDIA 6,092.00 180.00 74.37 25.63
APPS_TS_INTERFACE 13,177.63 366.38 71.49 28.51
The above works fine, but I would like to further change the query so that only those tablespaces with free space less than 5% (or used space more than 95%) are returned.
I have been working on this all morning and wanted to open it up to the masters!
I have tried using WHERE pct_used > 95 but to no avail.
Any advice would be appreciated.
Many thanks.
10.2.0.4
Linux Red Hat 4.Thanks for that.
What is confusing is that the below query works for every other (about 10 others) database but not this one (?)
SQL> set lines 200 pages 2000
SQL>
SQL> col tablespace_name heading 'Tablespace' format a30 truncate
SQL> col total_maxspace_mb heading 'MB|Max Size' format 9G999G999
SQL> col total_allocspace_mb heading 'MB|Allocated' format 9G999G999
SQL> col used_space_mb heading 'MB|Used' format 9G999G999D99
SQL> col free_space_mb heading 'MB|Free Till Max' like used_space_mb
SQL> col free_space_ext_mb heading 'MB|Free Till Ext' like used_space_mb
SQL> col pct_used heading '%|Used' format 999D99
SQL> col pct_free heading '%|Free' like pct_used
SQL>
SQL> break on report
SQL> compute sum label 'Total Size:' of total_maxspace_mb total_allocspace_mb used_space_mb - free_space_mb (used_space_mb/total_maxspace_mb)*100 on report
SQL>
SQL> select /*+ALL_ROWS */
2 alloc.tablespace_name,
3 alloc.total_maxspace_mb,
4 alloc.total_allocspace_mb,
5 (alloc.total_allocspace_mb - free.free_space_mb) used_space_mb,
6 free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb) free_space_mb,
7 free.free_space_mb free_space_ext_mb,
8 ((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
9 ((free.free_space_mb+(alloc.total_maxspace_mb-alloc.total_allocspace_mb))/alloc.total_maxspace_mb)*100 pct_free
10 FROM (SELECT tablespace_name,
11 ROUND(SUM(CASE WHEN maxbytes = 0 THEN bytes ELSE maxbytes END)/1048576) total_maxspace_mb,
12 ROUND(SUM(bytes)/1048576) total_allocspace_mb
13 FROM dba_data_files
14 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
15 GROUP BY tablespace_name) alloc,
16 (SELECT tablespace_name,
17 SUM(bytes)/1048576 free_space_mb
18 FROM dba_free_space
19 WHERE file_id NOT IN (SELECT FILE# FROM v$recover_file)
20 GROUP BY tablespace_name) free
21 WHERE alloc.tablespace_name = free.tablespace_name (+)
22 ORDER BY pct_used DESC
23 /
((alloc.total_allocspace_mb - free.free_space_mb)/alloc.total_maxspace_mb)*100 pct_used,
ERROR at line 8:
ORA-01476: divisor is equal to zero -
Different Result for SQL and PL/SQL query..need a bit of help
If i just run:
SELECT COUNT(*) from DB where (CLOSE_TIME-OPEN_TIME<5) and (CLOSE_TIME-OPEN_TIME>=1) and OPEN_TIME>'1/1/2011';
It works great.
If I run
BEGIN
SELECT COUNT(*) from DB where (CLOSE_TIME-OPEN_TIME<5) and (CLOSE_TIME-OPEN_TIME>=1) and OPEN_TIME>'1/1/2011';
END
I get the following error.
ORA-04052: error occurred when looking up remote object [email protected]
ORA-00604: error occurred at recursive SQL level 3
ORA-06552: PL/SQL: Compilation unit analysis terminated
ORA-06553: PLS-488: invalid variable declaration: object 'NUMBER' must be a type or subtype
ORA-02063: preceding 2 lines from SMGLINKHi,
Whenever you have a problem, post a complete test script that people can run to re-create the problem and test their ideas. Include CREATE TABLE and INSERT statements for any or your own tables needed.
Post the results you want from that sample data.
Always say which version of Oracle you're using.
bostonmacosx wrote:
If i just run:
SELECT COUNT(*) from DB where (CLOSE_TIME-OPEN_TIME<5) and (CLOSE_TIME-OPEN_TIME>=1) and OPEN_TIME>'1/1/2011';If OPEN_TIME is a DATE, then don't try to compare it to a string, such as '1/1/2011'. (This is not related to the present problem, only a future one.)
It works great.
If I run
BEGIN
SELECT COUNT(*) from DB where (CLOSE_TIME-OPEN_TIME<5) and (CLOSE_TIME-OPEN_TIME>=1) and OPEN_TIME>'1/1/2011';
END
I get the following error.
ORA-04052: error occurred when looking up remote object [email protected]
ORA-00604: error occurred at recursive SQL level 3
ORA-06552: PL/SQL: Compilation unit analysis terminated
ORA-06553: PLS-488: invalid variable declaration: object 'NUMBER' must be a type or subtype
ORA-02063: preceding 2 lines from SMGLINKI would expect a different error "PLS_00428: an INTO clause is expected". -
A Oracle sql query is needed, please help me out
Hi,
I have a table similar to scott.emp table and i should get first three recently joined employees salaries according to their joined date from each deptno
output should like this:
deptno firstempsalary secondemplsal thirdemploysalary
10 xxx xxx xxxx
20 xx xx
30 xx xxx xxxx
40 xx
50 xx xxxx xxx
60 xx xx
70 xx
it means that 70 dept having only one employee and 20 dept having only two employees and 10 dept having more than three employees but we should get only three recently joined employees salaries from 10 dept.
Hope this is clear .. please give me a query to get this info ..
oracle is 10g version
great thanks in advance.select deptno,
max(case jd_rank when 1 then salary end) firstempsal,
max(case jd_rank when 2 then salary end) secondempsal,
max(case jd_rank when 3 then salary end) thirdempsal
from
(select salary, deptno, row_number() over(partition by deptno order by join_date desc) jd_rank from emp)
group by deptno
Problem here is what to do when employees have the same join date? This example will arbitrarily choose their order and if, for example, three employees share the same (most recent) join date then they will arbitrarily be classed as "first", "second" and "third". If four employees join at the same time, one of them will be ignored at random!
Edited by: user10548434 on 03-Dec-2008 06:27 -
can some one help me in Rewriting a query which i am just confused with the syntax
SELECT DISTINCT
sypro.code ,
sypro.usage,
sypro.user_create,
sypro.user_modif,
aprol.description,
sypro.VALUE,
TO_CHAR(sypro.modif_dttm,'dd/mm/yyyy') Changed_Date,
sypro.create_dttm Created_Date,
sypro.archv_flag
FROM system_profiles sypro, application_roles aprol
WHERE sypro.APROL_REFNO = aprol.APROL_REFNO
AND sypro.modif_dttm>=TO_DATE('01/05/2006','dd/mm/yyyy')
AND sypro.CREATE_DTTM >=('01/05/2006','dd/mm/yyyy')
AND sypro.modif_dttm< TO_DATE('20/06/2006','dd/mm/yyyy') +1
AND sypro.create_dttm < to_date('20/06/2006','dd/mm/yyyy')+1
AND NVL(sypro.archv_flag , 'N') = 'N'
ORA-01797 the error msg is --this this operator is followed by any or allSorry for bothering all just found the error ....
thanks all -
Sql query tunning, need help!
below is the sql that runs very very slow:
SELECT h.STAT_HIST_ID, h.WF_ACTN, h.USR_ACTN,
h.WF_CHNG_DATA, h.USR_CHNG_DATA, h.PRCSG_TM, h.UPD_LOGIN, h.UPD_DT,
RTRIM(c.LAST_NM || ', ' || c.FIRST_NM || ' ' || c.MIDDLE_INITIAL)
FROM WF_STAT_HIST h, CSE_USER_DATA_VW c WHERE h.WRK_ITM_ID = 'GT1MPTG01ATBZP'
AND h.UPD_LOGIN = c.USER_NM (+) ORDER BY h.UPD_DT ;Here is its index:
all_indexes:
SCGDBA WF_STAT_HIST_INDX_ARCH NORMAL SCGDBA WF_STAT_HIST TABLE NONUNIQUE DISABLED IMS_I
SCGDBA PK_WF_STAT_HIST NORMAL SCGDBA WF_STAT_HIST TABLE UNIQUE DISABLED SCG_I
SCGDBA WF_STAT_HIST_IDX1 NORMAL SCGDBA WF_STAT_HIST TABLE NONUNIQUE DISABLED SCG_I
all_ind_columns:
SCGDBA WF_STAT_HIST_INDX_ARCH SCGDBA WF_STAT_HIST ARCHIVEDT 1 7 0 ASC
SCGDBA PK_WF_STAT_HIST SCGDBA WF_STAT_HIST STAT_HIST_ID 1 22 0 ASC
SCGDBA WF_STAT_HIST_IDX1 SCGDBA WF_STAT_HIST WF_ACTN 1 50 50 ASC
SCGDBA WF_STAT_HIST_IDX1 SCGDBA WF_STAT_HIST USR_ACTN 2 50 50 ASCHere is its explain plan:
Plan hash value: 479056202
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 216 | 30456 | 70864 (2)| 00:14:11 |
| 1 | SORT ORDER BY | | 216 | 30456 | 70864 (2)| 00:14:11 |
|* 2 | HASH JOIN OUTER | | 216 | 30456 | 70863 (2)| 00:14:11 |
|* 3 | TABLE ACCESS FULL| WF_STAT_HIST | 216 | 24840 | 70857 (2)| 00:14:11 |
| 4 | TABLE ACCESS FULL| CSE_USER_DATA_VW | 1013 | 26338 | 6 (0)| 00:00:01 |
Predicate Information (identified by operation id):
2 - access("H"."UPD_LOGIN"="C"."USER_NM"(+))
3 - filter("H"."WRK_ITM_ID"='GT1MPTG01ATBZP')Could you guys take a look and tell me what the problem might be?
I can`t give you TKPROF, because I got no access to that trace files!
Any thoughts would be appreciated:-)
Edited by: PhoenixBai on Sep 27, 2009 3:13 PMPl post the output of the following
select count(*) from wf_stat_hist;
select count (distinct wrk_itm_id) from wf_stat_hist;
select count (distinct upd_login) from wf_stat_hist;Your code is performing poorly because your WHERE clause is searching on a column on WF_STAT_HIST that is not indexed. Hopefully the output of the above code will determine which column (WRK_ITM_ID or UPD_LOGIN) is a better candidate to be indexed on. If neither of these columns is a good candidate, you may have to change the WHERE clause to be more selective rather than do a full table scan as the plan indicates.
HTH
Srini -
Sql query needed to verify force logging
Hi.
Does anyone out there have SQL query we need to run in order to see if our db is working in force logging mode?
Thanks.
DAThe FORCE_LOGGING column of v$database view can be queried to verify that the database is in FORCE LOGGING mode. Similarly, the FORCE_LOGGING column of dba_tablespace view provides the same information for each tablespace.
Kamran Agayev A. (10g OCP)
http://kamranagayev.wordpress.com
Maybe you are looking for
-
Iphone 5s - slider wont slide when receiving call. What do I do???
Hi - Both my mom and I have 2 week old iPhone 5s'. Both of us have had issues where it is often difficult to answer incoming calls. Its as if the slider is broken. I can often get the slider to slide, thus answering the call, right before it goes t
-
Embedding HTML in Fm12 to publish in RhHTML11
I have a Rh project that links to a Fm book. I'm trying to embed some html into Fm and have it show up in the Rh output. First item is a form. I'd like to have the form within the RH html files. I've tried to add the code to the Fm reference page in
-
HT201542 iPhone does not connect to a macmini
my iPhone 6 with the latest update refuses to connect to my Mac mini (2012) version. They recognize each other and I select pair but they refuse to accept the pairing acceptance. How do I fix this. (my iPad air works fine)
-
Using Data Compression on Microsoft SQL 2008 R2
We have a very large database which keeps growing and growing. This has made our upgrade process extremely troublesome because the upgrade wizard seems to require close to 3 times the database size of free space to even start. As such, we are conside
-
SAP report similar to CN41(cost overview report) in EUR
All, All figures shown on the cost overview report which is triggered from the project structure should be in company code currency NOT USD. Is there any config setting which will show results in company code currency but not at controlling area leve