HElp on TSQL query
Hi All,
I have Query like this when i select data from
Select * from @TempforBU
the result contains 9 rows. But next insert only 2 rows are inserting(As table is empty)
Declare @tempforBU table([partner_ID] Varchar(50) null ,DeleteBULevelCode Varchar(50) null,MDE_Expiry_Date Varchar(50) null,EndDate date null,[Comments] Varchar(100) null ) Insert Into @TempforBU Select [partner_ID] ,OLDBUlevelAcredCode as DeleteBULevelCode,
Expiry_Date as MDE_Expiry_Date, (Convert(Date,Getdate(),7)) as EndDate, 'Already Eligible for '+Eligible_AccredCode as [Comments] from [dbo].[P1_BULevel_GroupingData_4_Addition] Where Convert(Date,Expiry_Date,7)>Convert(Date,Getdate(),7) Select * from
@tempforBU Insert Into P1_BULevel_GroupingData_4_Deletion Select TB.* from @TempforBU TB left Join [P1_TopLevel_GroupingData_4_Deletion] TD On TB.[Partner_ID]=TD.Partner_ID where TD.[Partner_ID] is null
Can anyone correct this?
Hi All,
I have Query like this when i select data from
Select * from @TempforBU
the result contains 9 rows. But next insert only 2 rows are inserting(As table is empty)
Declare @tempforBU table([partner_ID] Varchar(50) null ,DeleteBULevelCode Varchar(50) null,MDE_Expiry_Date Varchar(50) null,EndDate date null,[Comments] Varchar(100) null ) Insert Into @TempforBU Select [partner_ID] ,OLDBUlevelAcredCode as DeleteBULevelCode,
Expiry_Date as MDE_Expiry_Date, (Convert(Date,Getdate(),7)) as EndDate, 'Already Eligible for '+Eligible_AccredCode as [Comments] from [dbo].[P1_BULevel_GroupingData_4_Addition] Where Convert(Date,Expiry_Date,7)>Convert(Date,Getdate(),7) Select * from @tempforBU
Insert Into P1_BULevel_GroupingData_4_Deletion Select TB.* from @TempforBU TB left Join [P1_TopLevel_GroupingData_4_Deletion] TD On TB.[Partner_ID]=TD.Partner_ID where TD.[Partner_ID] is null
Can anyone correct this?
I am assuming that you need an incremental load. That is non duplicates. Obviously we can not run this script since we don't have the DDL and DML for
'dbo.P1_BULevel_GroupingData_4_Addition',
thus just a guess.
Your table variable have 9 rows (Stated by you), and now when you do a left join with the object you are getting 2 rows (Stated by you). It implies that other 7 records are already there in that object<You are doing a left join with>.
Please use Mark as Answer; if my reply solved your problem. Use Vote As Helpful if a post was useful. |WWW.FACEBOOK.COM/SONNIE.HIM | |+91-9742-354-384 |
Similar Messages
-
Hi,
I want to design query. Below are the required:
Existing Table :
Code Val1 Val2 Val3
A A11 - -
B - B22 -
C - - C33
Output required:
Code Col1 Col2
A A11 B22
B B22 C33
C C33 -
Can anyone help with the query?Why don't you normalize your data?
E.g.
DECLARE @Sample TABLE
Code CHAR(1) ,
Val1 CHAR(3) ,
Val2 CHAR(3) ,
Val3 CHAR(3)
INSERT INTO @Sample
VALUES ( 'A', 'A11', NULL, NULL ),
( 'B', NULL, 'B22', NULL ),
( 'C', NULL, NULL, 'C33' );
-- SQL Server 2012+
WITH Normalized
AS ( SELECT U.Code ,
U.Attribute ,
U.Value
FROM @Sample S UNPIVOT ( Value FOR Attribute IN ( Val1, Val2, Val3 ) ) U
SELECT N.Code ,
N.Value ,
LEAD(N.Value, 1, NULL) OVER ( ORDER BY N.Code ASC )
FROM Normalized N;
-- SQL Server 2008+
WITH Normalized
AS ( SELECT U.Code ,
U.Attribute ,
U.Value ,
ROW_NUMBER() OVER ( ORDER BY U.Code ) AS RN
FROM @Sample S UNPIVOT ( Value FOR Attribute IN ( Val1, Val2, Val3 ) ) U
SELECT L.Code ,
L.Value ,
R.Value
FROM Normalized L
LEFT JOIN Normalized R ON L.RN = R.RN - 1;
btw, post in future concise and complete examples. Include table DDL and sample data INSERT statements as runnable T-SQL scripts. -
Hi all
One of our SQL jobs collects the SQLstatement which is running loner than 10 minutes by querying dm_exec_sql_text and dm_exec_sql_sessions.
Now the table has the similar records like below
SQL statementColumn
SELECT * FROM [DB].[dbo].[TABLE] WHERE column
Create procedure PRC1 @datefrom datetime @dateimeto = datetime, @scaleunit = varchar
…. Select top 1 from tbl_table1 select top from tbl_table2 ….
Declare @datefrom datetime select col1 , col2 from table3 where datetime = @datetime….
Now we wanted to aggregate the data and see what are all the table hitting heavily and what type of queries like adhoc or procedures or view
how to pull the tabe information and aggregate them together to see how much time similar type of queries are running in a day and how much time it took
completion on day wise or week wise
thanks
JyothiTry this, the query gives the details of most expensive queries along with number of execution count, logical reads, logical writes and elapsed time (secs). The one thing it doesn't directly provide about object type whether it is procedure, view
or adhoc query but indirectly it gives the original sql text that is executed and actual sql syntax where the query is expensive. The Original Sql Syntax will specify whether it is procedure call or adhoc query call. Hope this will help you.
SELECT TOP 10
qt.Text as OriginalSqlText,
SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1) as ActualSqlExecutionQuery,
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_logical_reads DESC
Abhi.
Please click "Propose As Answer" if a post solves your problem or "Vote As Helpful"
if a post has been useful to you -
Hi all,
The previous query is absolutely ok.
The only thing i want to change is ...
get all the previous available ve1 AND NEW: if a AGNR has no ve1-instance, regardless get an ve1-instance with the agnr filled but f.e. the other fields empty
The grouping could made in reporting-logic later, and not in the tsql-query.
resultset i need:
- all agnr, if the have an ve1-instance or not
Groups (hierarchy) i need, later in Report:
- AGNR
- ve1 (with all the left joind fields pg, vnfk, vnpk, vm (if they are)
- if a agnr has no instance of ve1 --> print: "NO ver available"
SELECT
ve1.new_verid,
ve1.new_no,
ve1.statuscode,
ve1.statuscodename,
ve1.createdon,
ve1.createdby,
ve1.createdbyname,
ve1.new_begin,
DATEPART(yyyy, ve1.new_begin) AS begin_year,
ve1.new_end,
ve1.new_vn_fid,
ve1.new_vn_fidname,
ve1.new_vn_kid,
ve1.new_vn_kidname,
vnpk.new_how_old,
ve1.new_vg,
ve1.new_vgname,
ve1.new_vs,
ve1.new_vsname,
ve1.new_vstat,
ve1.new_vstatname,
ve1.new_zw,
ve1.new_zwname,
ve1.new_bn_zw,
ve1.new_rlz_v,
ve1.new_pgid,
ve1.new_pgidname,
pg.accountnumber as pg_accountno,
ve1.new_agnr_agnr_avmid,
ve1.new_agnr_agnr_avmidname,
AGNR.new_vm_kid AS vm_contactid,
AGNR.new_vm_kidname AS vm_contactidname,
ve1.new_efv,
ve1.new_efvname,
CASE
WHEN ve1.new_vn_kid IS NOT NULL THEN 'Private Customer'
WHEN ve1.new_vn_fid IS NOT NULL THEN 'Account Customer'
ELSE 'Kunde'
END AS kunde_typ,
DATEPART(yyyy, vnpk.birthdate) as vnpk_birth_year,
CASE
WHEN ((ve1.new_rlz_v IS NOT NULL) OR (ve1.new_rlz_v > 0))
THEN ve1.new_rlz_v
WHEN (DATEPART(yyyy, ve1.new_begin) IS NOT NULL) AND (DATEPART(yyyy, vnpk.birthdate) IS NOT NULL)
THEN 65 - ((DATEPART(yyyy, ve1.new_begin)) - (DATEPART(yyyy, vnpk.birthdate)))
ELSE 20
END AS vlz_calc,
CASE
WHEN ((ve1.new_bnj IS NOT NULL) OR (ve1.new_bnj > 0)) THEN ve1.new_bnj
WHEN ((ve1.new_bn_zw IS NOT NULL) OR (ve1.new_bn_zw > 0))
THEN
CASE
WHEN new_zw = '100000008' THEN ve1.new_bn_zw * 12
WHEN new_zw = '100000004' THEN ve1.new_bn_zw * 4
WHEN new_zw = '100000002' THEN ve1.new_bn_zw * 2
WHEN new_zw = '100000001' THEN ve1.new_bn_zw * 1
WHEN new_zw = '100000006' THEN ve1.new_bn_zw
ELSE 0
END
ELSE 0
END AS bnj_calc
FROM
Filterednew_ver AS ve1
LEFT OUTER JOIN Filterednew_agnr AS AGNR
ON ve1.new_agnr_agnr_avmid = AGNR.new_agnrid
LEFT OUTER JOIN FilteredAccount AS pg
ON ve1.new_pgid = pg.accountid
LEFT OUTER JOIN FilteredAccount AS vnfk
ON ve1.new_vn_fid = vnfk.accountid
LEFT OUTER JOIN FilteredContact AS vnpk
ON ve1.new_vn_kid = vnpk.contactid
LEFT OUTER JOIN FilteredContact AS vm
ON AGNR.new_vm_kid = vm.contactid
WHERE
(ve1.createdon >= @Begin_Week)
AND (ve1.createdon <= @End_Week)
AND (ve1.new_vg = @vg)
AND (ve1.statuscode = '1')
AND (ve1.new_efv <> '100000000' OR ve1.new_efv IS NULL)
AND (ve1.new_vstat <> '100000004' OR ve1.new_vstat IS NULL)
AND (ve1.new_zw IN ('100000008','100000004','100000002','100000001','100000006'))
ORDER BY
ve1.createdon
i thought, and tried with right joins, but i think i need to change the sight (the complete query)?
thx for all kind of help
Greets PebHi Peb,
Please provide sample data and expected results. -
Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
create table #one (code_p char(4), code_h char(2), code_date datetime)
insert into #one values ('DEHG','2','2010-01-01')
insert into #one values ('DEHG','2','2011-01-01')
insert into #one values ('DEHC','2','2009-01-01')
insert into #one values ('DEHG','2','2012-01-01')
create table #two (code_p char(4), code_h char(2), code_date datetime)
insert into #two values ('DEHG','2','2010-01-01')
insert into #two values ('DEHC','2','2009-01-01')
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
--Result from the above query
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG 2 2010-01-01 DEHG 2 2010-01-01
DEHG 2 2011-01-01 DEHG 2 2010-01-01
DEHC 2 2009-01-01 DEHG 2 2009-01-01
DEHC 2 2012-01-01 DEHG 2 2009-01-01
--Desired result
code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
DEHG 2 2010-01-01 DEHG 2 2010-01-01
DEHG 2 2011-01-01 DEHG 2 -
DEHC 2 2009-01-01 DEHG 2 2009-01-01
DEHC 2 2012-01-01 DEHG 2 -Try this:
select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
from #one p
left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
If this post answers your query, please click "Mark As Answer" or "Vote as Helpful". -
Hello all,
Total newbie to this pl/sql stuff. So, deseperately need help in my query.
BOOKING_ID BOOKING_STATUS BOOKING_DATE BOOKING_TIME BOOKING_DATE_TIME
1234567 CANCELLED 20090301 37252 5/1/2010 10:20
1234567 CANCELLED 20090301 44229 5/1/2010 12:17
1234567 BOOKED 20090301 39462 5/1/2010 10:57
1234567 CANCELLED 20090301 43549 5/1/2010 12:05
9671111 BOOKED 20090301 68124 5/1/2010 12:57
9671111 CANCELLED 20090301 45001 5/1/2010 12:05
How do I write my query such that I would get the following results:
BOOKING_ID BOOKING_STATUS BOOKING_DATE BOOKING_TIME BOOKING_DATE_TIME
9671111 BOOKED 20090301 68124 2/4/2010 12:17
Basically, I am looking at the latest BOOKING_TIME and making sure the BOOKING_STATUS=BOOKED, if not, don't even bother bring back the result. Hence, you see that BOOKING_ID=1234567 is not required since at the latest BOOKING_TIME=44229, the BOOKING_STATUS=CANCELLED.
Any help is greatly appreciated.
Thank you in advance for your help.
Stanley HoHi, Stanley,
Welcome to the forum!
Whenever you have a question, please post your sample data in a form that people can actually use. CREATE TABLE and INSERT statements are perfect.
For example:
CREATE TABLE booking
( booking_id NUMBER (8)
, booking_status VARCHAR2 (10)
, booking_date_time DATE
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 10:20', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 12:17', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'BOOKED', TO_DATE ('5/1/2010 10:57', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (9671111, 'BOOKED', TO_DATE ('5/1/2010 12:57', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (9671111, 'CANCELLED', TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));What you want is called a Top-N Query .
Here's one way to do it:
WITH got_rnum AS
SELECT booking.*
, ROW_NUMBER () OVER ( PARTITION BY booking_id
ORDER BY booking_date_time DESC
) AS rnum
FROM booking
SELECT booking_id
, booking_status
, TO_CHAR (booking_date_time, 'YYYYMMDD') AS booking_date
, TO_CHAR (booking_date_time, 'SSSSS') AS booking_time
, TO_CHAR (booking_date_time, 'MM/DD/YYYY HH24:MI') AS booking_date_time
FROM got_rnum
WHERE rnum = 1
AND booking_status = 'BOOKED'
;Notice that you don't need PL/SQL to do this; plain old SQL is good enough.
Of course, if you're using PL/SQL for other reasons, you can use a query like this within PL/SQL.
Dates (including time of day) should always be stored in DATE columns.
If you have a DATE column, like booking_date_time, then there's no need for redundant date and time columns.
You can always display just the year-month-day, or just the time, in any format, as I did above.
The output from the query above, with the data above, is:
BOOKING_ID BOOKING_ST BOOKING_ BOOKI BOOKING_DATE_TIM
9671111 BOOKED 20100501 46620 05/01/2010 12:57I realize the booking_date and booking_time columns aren't quite what you posted. If they are not derivable from booking_date_time, then you probably do need separate columns for them, and those columns can easily be added to the query above.
Edited by: Frank Kulash on Feb 5, 2010 4:41 PM
KEEP (DENSE_RANK ...) , like Max used below, is a great tool to have in your kit. The problem with it is that you have to repeat a lot of stuff for every column, so the more columns you have in your output, the more tedious it gets. ROW_NUMBER sclaes much better, and is adaptable to more situations. I suggest you master ROW_NUMBER first, and look into KEEP (DENSE_RANK ...) later. -
I need help with SQL query (if it can be accomplished with query at all).
I'm going to create a table with structure similar to:
Article_Name varchar2(30), Author_Name varchar2(30), Position varchar2(2). Position field is basicly position of an article author in the author list, e.g. if there is one author, his/her position is 0, if 2, then 1st author is 0, second is 1, etc.
Article_Name Author_Name Position
Outer Space Smith 0
Outer Space Blake 1
How can I automate creation of Position, based on number of authors on the fly? Let's say I have original table without Position, but I want to create a new table that will have this information.
RegardsIf you have an existing table whose structure doesn't tell you what position the author is in, what's the algorithm you'd use to determine who was the first author, the second author, etc? If you issue a select query on a table without providing an "order by" clause, Oracle makes no guarantees about the order in which it retrieves rows.
As an aside, why would you store position number in a varchar2 field? If it's a number, it ought to be stored as a number.
Justin -
Need help with SQL Query with Inline View + Group by
Hello Gurus,
I would really appreciate your time and effort regarding this query. I have the following data set.
Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
Please Ignore '----', added it for clarity
I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
The query should return the following data set
Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
The following is my query. I am kind of lost.
select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
from (
select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
from INVOICE
group by sequence_id,check_date, check_number, invoice_number, vendor_number
) A, INVOICE B
where A.sequence_id = B.sequence_id
Thanks,
NickIt looks like it is a duplicate thread - correct me if i'm wrong in this case ->
Need help with SQL Query with Inline View + Group by
Regards.
Satyaki De. -
Hi,
I have a client requirement to show a report on the device availability. The report should show the output as
Node Availability%
Formula for Availability = (Total No. of Failed/Total No. rows) * 100
My Oracle Table has the following data
NODE SUMMARY
172.16.10.55 Default Interface Ping fail for 172.16.10.55: ICMP timeout
172.16.10.55 Default Interface Ping restore for 172.16.10.55
172.16.10.55 Default Chassis Ping restore for 172.16.10.55
172.16.10.55 Default Chassis Ping fail for 172.16.10.55: ICMP timeout
172.16.10.55 Default Chassis Ping restore for 172.16.10.55
172.16.10.55 Default Chassis Ping fail for 172.16.10.55: ICMP timeout
172.16.10.55 Default Chassis Ping fail for 172.16.10.55: ICMP timeout
172.16.10.55 Default Interface Ping restore for 172.16.10.55
172.16.10.55 Default Interface Ping fail for 172.16.10.55: ICMP timeout
172.16.10.56 Default Chassis Ping restore for 172.16.10.56
172.16.10.56 Default Interface Ping fail for 172.16.10.56: ICMP timeout
172.16.10.56 Default Chassis Ping fail for 172.16.10.56: ICMP timeout
172.16.10.56 Default Chassis Ping restore for 172.16.10.56
172.16.10.56 Default Chassis Ping fail for 172.16.10.56: ICMP timeout
172.16.10.56 Default Chassis Ping restore for 172.16.10.56
172.16.10.56 Default Chassis Ping restore for 172.16.10.56
172.16.10.56 Default Interface Ping fail for 172.16.10.56: ICMP timeout
In the above table the Summary column has the details like 'Ping fail' , 'Ping restore' for each Node. So, for each Node I have to compute the Total Ping Fail / (Total Ping Fail + Ping Restore) * 100 to compute the availability %.
My output should be like the below
Node Availability%
172.16.10.55 55.55
172.16.10.56 54
Can someone please help me with query.
I appreciate your help in advance.
Thanks.
Regards,
RaviShankar.My Oracle Table has the following dataThat's great, but if you want maximum response to your question, then post CREATE TABLE + INSERT INTO statements.
I currently do not have the time to turn your data into them.
And always post the database version you're using.
http://tkyte.blogspot.com/2005/06/how-to-ask-questions.html
Also use the {noformat}{noformat} tag in order to post examples that benefit from staying formatted and thus readable when posted on the forum.
Simply put the tag before and after your examples.
For example, when you type:
{noformat}select *
from dual;{noformat}
it will appear as:select *
from dual; -
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. -
Can we Definine Input Help in a Query
Hi
Is it possible to define input help or search help in a query the same way as it is done in R3?? I will like to load specific value from a psa.
RegardsHi Jacques,
Providing Customized Input help in query directly is not possible. Instead we can provide Input help in WAD layouts for a query with the help of another Query.
This can be made available for the users to choose with using controls such as Drop Down, Check boxes, Buttons and so on..
Hope this helps.
Regards.
Shafi. -
I need help with the query
Here is what I need
For a particular comm record if there is no Salary record where comm:Date = Salary:Date, then
• Find maximum dated Salary record as of comm:Date.
• Clone this record and set Salary:Date = comm:Date
• Set Salary:rate = comm:rate
Like wise for a particular Salary record If there is no comm record where Salary:Date = comm:Date then
• Find maximum effective dated comm record as of Salary:Date
• Apply Rate 2 amount from this maximum effective dated record to Salary record i.e. Set Salary:rate = comm:rate
Example
Salary Table :
ID Sal_Date Rate Hours
1 07/01/2011 400.00 40
2 02/15/2011 200.00 40
3 01/01/2011 160.00 40
Sal_comm Table:
Sal_Date comm_Rate
1 07/01/2011 10.00
4 03/01/2011 7.50
3 01/01/2011 4.00
I need to merge comm_Rate column in Salary table, since there is no salary record as off 03/01/2011, I need to find the maximum dated salary record as of 03/01/2011
i.e. the record dated 02/15/2011. Now I need to clone that salary record, set the SAL_date as 03/01/2011 and update Rate2 amount. So the record set will be like:
Sal_Date:
id sal_Date Rate Hours comm_Rate
1 07/01/2011 400.00 40 10.00
4 03/01/2011 200.00 40 7.50
2 02/15/2011 200.00 40 4.00
3 01/01/2011 160.00 40 4.00So you need all used dates as the "driving" dataset. And you need the according data for each of these.
WITH salary_table as
(select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,400 rate,40 hours from dual union all
select 2 id,to_date('02/15/2011','MM/DD/YYYY')sal_date,200 rate,40 hours from dual union all
select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,160 rate,40 hours from dual),
sal_comm as
(select 1 id,to_date('07/01/2011','MM/DD/YYYY')sal_date,10 comm_Rate from dual union all
select 4 id,to_date('03/01/2011','MM/DD/YYYY')sal_date,7.5 comm_Rate from dual union all
select 3 id,to_date('01/01/2011','MM/DD/YYYY')sal_date,4 comm_Rate from dual)
select to_char(all_dates.sal_date,'MM/DD/YYYY') sal_date,sal.rate,sal.hours,com.comm_rate
from (select sal_date from salary_table
union
select sal_date from sal_comm) all_dates
inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
from salary_table s1) sal
on (all_dates.sal_date between sal.sal_date and sal.next_sal_date)
inner join (select s1.*,lead(sal_date-1,1,to_date('31/12/9999','DD/MM/YYYY')) over (order by sal_date) next_sal_date
from sal_comm s1) com
on (all_dates.sal_date between com.sal_date and com.next_sal_date)
order by all_dates.sal_date desc;
SAL_DATE RATE HOURS COMM_RATE
07/01/2011 400 40 10
03/01/2011 200 40 7.5
02/15/2011 200 40 4
01/01/2011 160 40 4
-
Need urgent help with the query - Beginer
Hello - I need help with a query to populate data in a table.Here is the scenario.
Source1
MnthID BranchCod CustID SegCode FXStatus ProfStatus Profit
200712 B1 C1 20 Y Y 100
Source2
MnthID BranchCod CustID ProdCode ProdIndex
200712 B1 C1 12 1
200712 B1 C2 12 0
Destination
MnthID BranchCod SegCode ProdCode CountSegCust CountProdCust ProfitProdCust
Condition and Calculations:
1)Source1 customer are base customers.If Source2 has customers who is not in source1 then that customer's record should not be fetched.
2)SegCode, FX Status, ProfStatus is one variable in destination table. [ SegCode = SegCode+ FXStatus (if FXStatus = Y)+ ProfStatus (if FXStatus = Y) ]
3)CountSegCust = CountCustID Groupby MnthID,BranchCod,SegCode Only.
4)CountProdCust = CountCustID Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
5)ProfitProdCust = Sum of Profit of Customers Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
Apologies for bad formatting.
Thanks in advance!!A total guess indeed.
It's not clear whether some aggregation can be done (summing counts of grouped data might cause some customers being counted more than once)
insert into destination
select mnthid,branchcod,segcode,prodcode,countsegcust,countprodcust,profitprodcust
from (select s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end segcode,
s2.prodcode,
count(s1.custid) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
order by null
) countsegcust,
count(case proindex when 1
then custid
end
) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) countprodcust,
sum(case proindex when 1
then profit
end
) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) profitprodcust,
row_number() over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) the_row
from source1 s1,source2 s2
where s1.mnthid = s2.mnthid
and s1.branchcod = s2.branchcod
and s1.custid = s2.custid
where the_row = 1Regards
Etbin -
Need help writing a query for following scenario
Hi all, I need some help writing a query for the following case:
One Table : My_Table
Row Count: App 5000
Columns of Interest: AA and BB
Scenario: AA contains some names of which BB contains the corresponding ID. Some
names are appearing more than once with different IDs. For example,
AA BB
Dummy 10
Me 20
Me 30
Me 40
You 70
Me 50
Output needed: I need to write a query that will display only all the repeating names with their corresponding IDs excluding all other records.
I would appreciate any input. ThanksIs it possible to have a records with the same values for AA and BB? Are you interested in these rows or do you only care about rows with the same value of AA and different BB?
With a slight modification of a previous posting you can only select those rows that have distinct values of BB for the same value of AA
WITH t AS (
SELECT 'me' aa, 10 bb FROM dual
UNION ALL
SELECT 'me' aa, 20 bb FROM dual
UNION ALL
SELECT 'you' aa, 30 bb FROM dual
UNION ALL
SELECT 'you' aa, 30 bb FROM dual
SELECT DISTINCT aa, bb
FROM (SELECT aa, bb, COUNT(DISTINCT bb) OVER(PARTITION BY aa) cnt FROM t)
WHERE cnt > 1; -
Can anyone help me with Query ?
Hi Experts,
Can anyone help me with Query? the query need to retrieve below info based on set of books ID.
Needed columns:
1 SOB
2 Legal Entities
3 Fixed Asset Org Name
4 Applications/Responsibilities
5 Operating Units
6 Inventory Org
7 COA
8 Assigned Responsibilities
ThanksDuplicate post -- Can you help on below Query ?
Please post only once!
Maybe you are looking for
-
OS 9.2.2 system folder not recognised in tiger
Hi, I'm a bit lost here. I'm trying to get Classic to run in OS X 10.4.11. which has no previous copy of OS9 on it. The OS X was a clean install. I installed a copy of OS9.1 onto a USB dongle and then managed to boot the G3 through this and install O
-
When I go to load a texture in the Texturizer Filter from one that I created, I see a hard edge no matter how I scale it. I tried saving my created .psd textures at the same resolution as the presets, and even tried doubling the file size, but no mat
-
Hi. I keep installing the newest version of Firefox but when I open sites (iCloud, Paypal, etc...) they keep telling me that I don't have the latest version of Firefox installed. When I click on "About Firefox", I says I have version 7 installed...bu
-
I don't like iTunes as CD Player or anything else except Radio. This is the ONLY reason I use it. Usually I choose one station and minimize iTunes to tray or switch to Mini Player. And this is EXTREMELY annoying to do it each time I launch iTunes. Ar
-
I want to know about my phone whether it is factory unlocked or not???
Dear Concern, i want to know about my phone whether it is factory unlocked or not??? Need your kind support in this regards.