I need help in sql insert statement
sorry i cant speak English very well
======================
i have a table contains two columns date_2011 and salary
date_2011 || salary
====================
1-1-2011 || 1000$
2-1-2011 || 2000$
7-1-2011 || 500$
11-1-2011 || 200$
my question is
i need a sql statement to view Table as this table
FROM || TO || Total Salary
==================================
1-1-2011 || 2-1-2011 || 3000$
7-1-2011 || 11-1-2011 || 700$
try this
SQL> with t as
2 (
3 select to_date('1-1-2011','dd-mm-yyyy') date_2011, 1000 salary from dual union all
4 select to_date('2-1-2011','dd-mm-yyyy'), 2000 from dual union all
5 select to_date('7-1-2011','dd-mm-yyyy'), 500 from dual union all
6 select to_date('11-1-2011','dd-mm-yyyy'), 200 from dual
7 ), t2 as(
8 select
9 date_2011 as date_from ,
10 lead(date_2011, 1, null) over(order by date_2011) date_to,
11 salary + lead(salary, 1, null) over(order by date_2011) sal
12 , rownum rn
13 from t order by date_2011)
14 --
15 select date_from as" from", date_to as "to", sal as "Total Salary" from t2 where mod(rn,2) != 0;
from to Total Salary
01.01.11 02.01.11 3000
07.01.11 11.01.11 700
SQL>
Similar Messages
-
Hi,
I have a table with named as cust_pkg_tbl and data contains as below.scrcdall column contain comma separated strings.
id name memstatus mobileno srccdall
1001 kaushik 8 9876549032 cde1,cde2,cde3
1002 ram 4 8845670982 cde1,cde2
1003 raj 2 8823578432 cde1,cde2,cde3,cde4
1004 kumar 8 9630987654 cde1,cde2
Based on the above data client wants to insert as 3/4/2 separate records into the side/lookup table(src_cde_pkg_tbl) as below.
client wants the data looks like in the below table as src_cde_pkg_tbl.
id srt_num srccdall
1001 1 cde1
1001 2 cde2
1001 3 cde3
1002 1 cde1
1002 2 cde2
1003 1 cde1
1003 2 cde2
1003 3 cde3
1003 4 cde4
1004 1 cde1
1004 2 cde2
could you please help me to achieve the requirement.
thx in advanceYou've posted enough times to know you need to provide your 4 digit Oracle version.
>
Based on the above data client wants to insert as 3/4/2 separate records into the side/lookup table(src_cde_pkg_tbl) as below.
>
That similar question has been answered many times on the forum.
See the faq about converting rows to columns
SQL and PL/SQL FAQ
And search the forum for columns to rows. -
Need help with the session state value items.
I need help with the session state value items.
Trigger is created (on After delete, insert action) on table A.
When insert in table B at least one row, then trigger update value to 'Y'
in table A.
When delete all rows from a table B,, then trigger update value to 'N'
in table A.
In detail report changes are visible, but the trigger replacement value is not set in session value.
How can I implement this?You'll have to create a process which runs after your database update process that does a query and loads the result into your page item.
For example
SELECT YN_COLUMN
FROM My_TABLE
INTO My_Page_Item
WHERE Key_value = My_Page_Item_Holding_Key_ValueThe DML process will only return key values after updating, such as an ID primary key updated by a sequence in a trigger.
If the value is showing in a report, make sure the report refreshes on reload of the page.
Edited by: Bob37 on Dec 6, 2011 10:36 AM -
Looking for some help with building insert statements...
Hi, I am using some sql to build some insert statements for me to update a set of tables in our qa environments. The scripts that I have created were working great until someone added a column to some of the tables in the qa env which in turn makes my scripts break because I was simply building the statment to do someting like this...
insert into dest_table (select * from source_table@dblink);
But now when the coumns in the tables do not match it breaks...
This is the dynamic create script I use, can anyone help or suggest a better way to be able to build update statements update to qa tables when the columns are mismatched?
spool insert.sql
select
'insert into ' || table_name || ' (select * from ' || table_name || '@prod );' || chr(10) || ' commit;'
from user_tables
where table_name in
(select * from refresh_tablesl)
any help is greatly appreciated,
Thanks.See my reply to your duplicate post
looking for help building dynamic insert statements... -
Generate SQL Insert Statements
Hello,
I am testing generating insert statements for which I have a function which will return a sql statement.
This sql statement when I execute would results as sql insert statements.
What I am trying to acheive through a procedure is when I execute function, the result I would like to execute automatically and then the second sql I would like to store to a control file or sql file.
How can I acheive this?
Any help is very helpful
Regards
Edited by: user20090209 on Aug 20, 2009 11:34 AMHere is the function to generate sql
CREATE OR REPLACE function insert_sql(v_table_name varchar2)
return varchar2 as
b_found boolean := false;
v varchar2(32000);
v1 varchar2(32000);
v2 varchar2(32000);
begin
for s in (
select *
from all_tables
where table_name=upper(v_table_name)
--and owner=upper(v_owner)
) loop
b_found := true;
for ss in (
select *
from all_tab_columns
where table_name = s.table_name
order by column_id
) loop
if ss.data_type='NUMBER' then
v1:=v1||','||ss.column_name;
v2:=v2||',''''''||to_char('||ss.column_name||')||''''''';
end if;
if ss.data_type in ('VARCHAR2','CHAR') then
v1:=v1||','||ss.column_name;
v2:=v2||',''''''||replace(replace('||ss.column_name||','''''''',''''''''''''),''&'','''')||''''''';
end if;
if ss.data_type='DATE' then
v1:=v1||','||ss.column_name;
v2:=v2||',to_date(''''''||to_char('||ss.column_name||',''dd.mm.yyyy hh:mi:ss'')||'''''',''''dd.mm.yyyy hh:mi:ss'''')';
end if;
end loop;
v:='select ''insert into '||s.table_name||' (';
v:=v||substr(v1,2,9999)||') '||chr(10)||' values ('||substr(v2,2,9999)||'); '' txt from '||s.table_name;
end loop;
if not b_found then
v:='- Table ' || v_table_name || ' not found';
else
v:=v;
end if;
return v;
end;
/And I am calling like
CREATE OR REPLACE PROCEDURE test_gen_script_exec IS
type v_ref_cur is REF CURSOR;
v_ref_cur_var v_ref_cur;
v_temp_sql VARCHAR2(4000);
v_sql varchar2(4000);
begin
v_sql := insert_sql('table_name');--change here
open v_ref_cur_var for v_sql;
loop
fetch v_ref_cur_var into v_temp_sql;
exit when v_ref_cur_var%notfound;
execute immediate v_temp_sql;
end loop;
close v_ref_cur_var;
end;
/Edited by: user20090209 on Aug 20, 2009 1:24 PM -
I need help on bulk inserts....
Hello,
I need help on bulk inserts. I have heard about it but don't know how to do it and how to specify the number of records to be inserted at a time.
Can anyone please help me out?
For example: I would like to insert in my TEST_TABLE a group of data at tha same time...
INSERT INTO TEST_TABLE VALUES ( (1, 'xxx', 'www'), (2, 'yyy', 'hhh'), (3, 'aaa', 'kkk') )
I using Oracle 10g .
Tks!!
Message was edited by:
user532944
Message was edited by:
user532944But I want to insert a group of data at the same time, with one sql instruction...
I don´t know if exists this SQL command...I just know that I can insert
string sqlStmt = "INSERT INTO TESTE VALUES (:x, :x, :x)";
stmt = con->createStatement (sqlStmt);
But and this instruction ?? In MYSql I can do it!!
string sqlStmt = "INSERT INTO TESTE VALUES ((:x, :x, :x), (:x, :x, :x));
Message was edited by:
user532944 -
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. -
Urgent help needed... PL/SQL Insert statement
Hi...
I need some urgent help on this project. I have a 2 column table with values that need to be inserted into another existing table which has a sequence.
This is the 2 column table:
FUND YEAR
29587 05
29587 07
Existing table:
Name Null? Type
LIST_ID NOT NULL NUMBER(6) -- This is a sequence
WEB_USER_ID NOT NULL VARCHAR2(10)
RESOURCE_TYPE NOT NULL VARCHAR2(8)
LIST_TYPE NOT NULL VARCHAR2(10)
LIST_NAME NOT NULL VARCHAR2(50)
LIST_CODE_1 NOT NULL VARCHAR2(6) -- FUND from table above
LIST_CODE_2 NOT NULL VARCHAR2(6) -- YEAR from table above
LIST_CODE_3 NOT NULL VARCHAR2(6)
LAST_UPDATED_DT NOT NULL DATE
LAST_UPDATED_BY NOT NULL VARCHAR2(10)
LIST_CODE_4 NOT NULL VARCHAR2(20)
The columns from table 1 (FUND, YEAR) correspond to columns (LIST_CODE_1, LIST_CODE_2) in table 2. The column LIST_ID is a sequence. I can put in sysdate for LAST_UPDATED_DT and my initials SN for LAST_UPDATED_BY. This is going to be for 2 unique WEB_USER_IDs which would be in the WHERE clause. I will be inserting 2200 rows for each id. A single insert statement would look like this -
INSERT INTO EXISTING_TBL (list_id,web_user_id,resource_type,list_type,list_name,list_code_1,list_code_2,list_code_3,list_code_4,last_updated_dt,last_updated_by) VALUES ('470027','WEBUSER','GL','FUNDFYF',' FUND BALANCE SUM','12010','01',' ',' ',{ts '2010-5-19 10:16:9'},'SN')
How would I do this to insert the 2200 values from my 2 column table to the existing table?
All help is greatly appreciated!!
SNHello ,
I think this will work
INSERT INTO TABLE2
LIST_ID,
WEB_USER_ID,
RESOURCE_TYPE,
LIST_TYPE,
LIST_NAME,
LIST_CODE_1,
LIST_CODE_2,
LIST_CODE_3,
LIST_CODE_4,
LAST_UPDATED_DT,
LAST_UPDATED_BY
SELECT
SEQ.NEXTVAL,
FUND,
YEAR,
<VALUE FOR RESOURCE_TYPE>,
<VALUE FOR LIST_TYPE>,
<VALUE FOR LIST_NAME>,
<VALUE FOR LIST_CODE_1>,
<VALUE FOR LIST_CODE_2>,
<VALUE FOR LIST_CODE_3>,
<VALUE FOR LIST_CODE_4>,
SYSDATE,
'SN'
FROM
TABLE1
REGARDS
Rahul Sharma -
Hi,
Need help to write sql statement.
create table t_dt ( dt_start date, dt_end date, amount number);
insert into t_dt values('1-Jan-10','10-Feb-10',12);
insert into t_dt values('11-Feb-10','10-Mar-10',10);
insert into t_dt values('11-Mar-10','20-Apr-10',8);
insert into t_dt values('21-Apr-10','28-Jun-10',10);
insert into t_dt values('29-Jun-10','20-Sep-10',10);
insert into t_dt values('21-Sep-10','10-Oct-10',10);
insert into t_dt values('11-Oct-10','31-Dec-10',8);
insert into t_dt values('1-Jan-11','10-Feb-11',8);
insert into t_dt values('11-Feb-11','10-Mar-11',7);
insert into t_dt values('11-Mar-11','20-Apr-11',6);
insert into t_dt values('21-Apr-11','28-Jun-11',6);
insert into t_dt values('29-Jun-11','20-Sep-11',6);
insert into t_dt values('21-Sep-11','10-Oct-11',4);
insert into t_dt values('11-Oct-11','31-Dec-11',8);
Result should be like below..
dt_start dt_end Amount
1-Jan-10 10-Feb-10 12
11-Feb-10 10-Mar-10 10
11-Mar-10 20-Apr-10 8
21-Apr-10 10-Oct-10 10
11-Oct-10 10-Feb-11 8
11-Feb-11 10-Mar-11 7
11-Mar-11 20-Sep-11 6
21-Sep-11 10-Oct-11 4
11-Oct-11 31-Dec-11 8
Just to explain the example, take a row with start date as 21-Apr-10 in the above insert statements, since it has the same amount for next two rows (i.e. with start date '29-Jun-10' and '21-Sep-10') these 3 rows should be converted to represent only 1 row in the result and the start date and end date should be changed per the result shown above.
Thanks.Hello
I think this gives yuo what you need....
SELECT
MIN(dt_start),
MAX(dt_end),
amount
FROM
( SELECT
dt_start,
dt_end,
MAX(marker) OVER(ORDER BY dt_start) marker,
amount
FROM
Select
dt_start,
dt_end,
amount,
CASE
WHEN LAG(amount) OVER(ORDER BY dt_start) <> amount THEN
ROW_NUMBER() OVER(ORDER BY dt_start)
END marker
from t_dt
GROUP BY
amount,
marker
order by
MIN(dt_start)
MIN(DT_START) MAX(DT_END) AMOUNT
01-JAN-2010 00:00:00 10-FEB-2010 00:00:00 12
11-FEB-2010 00:00:00 10-MAR-2010 00:00:00 10
11-MAR-2010 00:00:00 20-APR-2010 00:00:00 8
21-APR-2010 00:00:00 10-OCT-2010 00:00:00 10
11-OCT-2010 00:00:00 10-FEB-2011 00:00:00 8
11-FEB-2011 00:00:00 10-MAR-2011 00:00:00 7
11-MAR-2011 00:00:00 20-SEP-2011 00:00:00 6
21-SEP-2011 00:00:00 10-OCT-2011 00:00:00 4
11-OCT-2011 00:00:00 31-DEC-2011 00:00:00 8
9 rows selected.HTH
David
Edited by: Bravid on Feb 23, 2012 12:08 PM
Beaten to it by Frank! :-) -
I am using Sybase as my back end database. I need help on my SQL statement regarding datetime. The datetime is store as a 9 digit integer in the database (...I believe it is a Decimal(30,6) format, let me know if I am wrong).
If I do this, "select * from mytable;" It works out fine (except I don't know what the date means e.g. 998919534)
If I do this, "select * from mytable where datetime_col < '9/5/2002' ; I got an error. I even tried '9/5/02 11:00 000 am' but it didn't help.
How do I specify a date or datetime in my query?
Thanks in advance.I execute the sql statement
select * from mytable where datetim_col < convert(datetime, '3/4/2002', 101) ;
I got mix result. I got an error message "cannot convert 10375584 to a date.
Yet, he statistics window of the I-sql says
"estimated 493 rows in query (I/O estimate 87)
PLan> mytable (seq)"
It looks like I my the SQL statement is correct and then the system can't display it in the Data window.
Any thought ? -
Need help on SQL Statement for UDF
Hi,
as I am not so familiar with SQL statements on currently selected values, I urgently need help.
The scenario looks as follows:
I have defined two UDFs named Subgroup1 and Subgroup2 which represent the subgroups dependent on my article groups. So for example: When the user selects article group "pianos", he only sees the specific subgroups like "new pianos" and "used pianos" in field "Subgroup1". After he has selected one of these specific values, he sees only the specific sub-subgroups in field "Subgroup2", like "used grand pianos".
I have defined UDTs for both UDFs. The UDT for field "Subgroup1" has a UDF called "ArticleGroup" which represents the relation to the article group codes. The UDT for field "Subgroup2" has a UDF called "Subgroup1" which represents the relation to the subgroups one level higher.
The SQL statement for the formatted search in field "Subgroup1" looks as follows:
SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP1] T0 WHERE T0.[U_ArticleGroup] = (SELECT $[OITM.ItmsGrpCod])
It works fine.
However, I cannot find the right statement for the formatted search in field "Subgroup2".
Unfortunately this does NOT WORK:
SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP2] T0 WHERE T0.[U_Subgroup1] = (SELECT $[OITM.U_Subgroup1])
I tried a lot of others that didn't work either.
Then I tried the following one:
SELECT T0.[Name] FROM [dbo].[@B_SUBGROUP2] T0 WHERE T0.[U_Subgroup1] = (SELECT T1.[Code] FROM [dbo].[@B_SUBGROUP1] T1 WHERE T1.[U_ArticleGroup] = (SELECT $[OITM.ItmsGrpCod]))
Unfortunately that only works as long as there is only one specific subgroup1 for the selected article group.
I would be sooooo happy if there is anyone who can tell me the correct statement for my second UDF!
Thanks so much in advance!!!!
Edited by: Corinna Hochheim on Jan 18, 2010 10:16 PM
Please ignore the "http://" in the above statements - it is certainly not part of my SQL.
Please also ignore the strikes.Hello Dear,
Use the below queries to get the values:
Item Sub Group on the basis of Item Group
SELECT T0.[Name] FROM [dbo].[@SUBGROUP] T0 WHERE T0.[U_GroupCod] =$[OITM.ItmsGrpCod]
Item Sub Group 1 on the basis of item sub group
SELECT T0.[Name] FROM [dbo].[@SUBGROUP1] T0 WHERE T0.[U_SubGrpCod]=(SELECT T0.[Code] FROM [dbo].[@SUBGROUP] T0 WHERE T0.[Name] =$[OITM.U_ItmsSubgrp])
Sub group 2 on the basis of sub group 1
SELECT T0.[Name] FROM [dbo].[@SUBGROUP2] T0 WHERE T0.[U_SubGrpCod1]=(SELECT T0.[Code] FROM [dbo].[@SUBGROUP1] T0 WHERE T0.[Name] =$[OITM.U_ItmsSubgrp1])
this will help you.
regards,
Neetu -
Help needed in forming dynamic insert statement
HI,
I am trying to construct a insert statement as given below.
Please help me as to how to form this and where am i going wrong?
i want the columns names to be auto populated when a table name is given.
output should be like:
==============
insert into tablename
col1,col2,col3..coln)
values
(col1, col2, col3..coln);
declare
v_sql varchar2(5000);
cnt number :=0;
col_count number;
name varchar2(5000);
TYPE string_assarrtype IS TABLE OF VARCHAR2 ( 25 ) INDEX BY VARCHAR2 ( 20 );
arr string_assarrtype;
BEGIN
select count(column_name) into col_count from user_tab_columns
where
table_name = 'PS_D_RE_BCSREGIONMAPPING';
v_sql:='insert into tablename (' ;
for i in 1..arr(col_count)
loop
v_sql:='v_sql' ||' '||arr(i);
DBMS_OUTPUT.PUT_lINE(v_sql);
END LOOP;
END;Below is the actual code which i am trying to write:
Since the below trigger logic is same for around 25/30 tables i wanted to construct a generic procedure which will take input parameter as tablename and auit_table and form the insert statement which will populate the column names which are different for different tables.
Please guide...
CREATE OR REPLACE PROCEDURE make_trigger( tablename in VARCHAR2,
auditable in VARCHAR2
AS
v_sql varchar(10000);
begin
v_sql := 'DROP TRIGGER TRD_D_AUDIT_D'||tablename;
dbms_output.put_line (v_sql );
v_sql:='CREATE OR REPLACE TRIGGER TRG_D_AUDIT_D_'||tablename||' '||
'BEFORE INSERT OR UPDATE OR DELETE ON 'tablename||' '||' REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW';
dbms_output.put_line (v_sql );
v_sql:= 'DISABLE
DECLARE
v_Operator psoprdefn.oprid%type;
v_Sysdate Date;
v_Actn varchar2(1);
V_AUDIT_RECNAME PSRECDEFN.RECNAME%type;
BEGIN';
dbms_output.put_line (v_sql );
v_sql:= 'If (Inserting) Then
v_Actn :='||'''||'A'||'''||';'||
'Insert into '||auditable||'
('||
AUDIT_RECNAME,
AUDIT_ACTN,
AUDIT_OPRID,
AUDIT_STAMP,
D_USER_GROUP,
D_GROUP_DESC,
D_BCS_ID,
D_UBR_ID,
D_FILTER_ID,
D_NAME_ACCESS_TYPE,
D_GLOBAL_EMP_LIST
Values
V_AUDIT_RECNAME,
v_Actn,
v_Operator,
v_Sysdate,
:NEW.D_USER_GROUP,
:NEW.D_GROUP_DESC,
:NEW.D_BCS_ID,
:NEW.D_UBR_ID,
:NEW.D_FILTER_ID,
:NEW.D_NAME_ACCESS_TYPE,
:NEW.D_GLOBAL_EMP_LIST
end if;
end;Edited by: user11942774 on Oct 5, 2012 11:46 AM
Edited by: user11942774 on Oct 5, 2012 8:09 PM
Edited by: user11942774 on Oct 5, 2012 8:10 PM -
SQL insert statement help please
alternative is to have the table with field dateadd with default value of getdate() - then do not include in your insert statement - then the modify date use and update - starting point - my two cetns
Hi all I'm trying to go a little out of my comfort level here and was hoping for some advice. I have a sql table that has 2 date fields. an add and a modified. If the modified date is null then I want to calculate on the date added. Otherwise I'd like to calculate on the modified date.
Here is a simplified version of what I'm trying to accomplish.
Hope it makes sense what I'm trying to do.
SQLSELECT field1,field2.... ,dateAdded , dateModifiedINTO tblOutputFROM tblInput/* some pseudo code here */WHERE (if dateModified not null then ( dateModified -
Improving SQL Insert statement syntax
It's about insert statement syntax, in insert statement, unlike in update statement column names and corresponding values are separated in two different sets. With this separation debugging/writing of insert statement is going to be time taking activity. To identify what value is getting stored in any column, first column position needs to be identified and after that by counting commas in the values list value is located. If functions are included in insert statement then counting of commas doesn't help to locate the value.
In any non trivial application column count in insert statement is going to be very big number and it is unmanageable.
If column name and value are written next to each other as it is done in cause of UPDATE statement, it is going to drastically reduce the debugging efforts and there by improves the productivity of the developers.
So I request SQL community please consider having a variant of insert statement in similar lines of update statement. This will simplify the life of millions of developers.
Edited by: user9110509 on Feb 6, 2010 10:19 AMHi,
That's a good idea! An optional alternate way of specifying the columns would be handy.
Perhaps the reason it hasn't been done yet is that most people, like those who have responded to this message, do not find the current syntax much of a problem. We can't be sure if your idea "is going to drastically reduce the debugging efforts" until it is available, but my guess is that it isn't.
One thing I do to make sure the two lists match is to indent the values directly below the column names, like this:
INSERT INTO emp (empno, ename, hiredate, job)
VALUES (9876, 'OBAMA', TO_DATE ( '20-JAN-2009'
, 'DD-MON-YYYY), 'PRESIDENT');If the list is very long, or individual values are very complicated, then I might start with a list of the column names
INSERT INTO emp -- Step 1: not ready to run yet
( empno
, ename
, hiredate
, job
VALUESthen use the editor's copy and paste commands to duplicate that list:
INSERT INTO emp -- Step 2: not ready to run yet
( empno
, ename
, hiredate
, job
VALUES
( empno
, ename
, hiredate
, job
;and then fill in the VALUES section, leaving the copied names as comments:
INSERT INTO emp -- Step 3: ready to run
( empno
, ename
, hiredate
, job
VALUES
( 9876 -- empno
, 'OBAMA' -- ename
, TO_DATE ( '20-JAN-2009'
, 'DD-MON-YYYY
) -- hiredate
, 'PRESIDENT' -- job
; -
Need Help With SQL GROUP BY and DISTINCT
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Hi,
user12036843 wrote:
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Sorry, it's unclear what you want.
Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.
Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
Here's an example of how to use GROUP BY GROUPING SETS.
Way we're interested in employees' salary and commission from the scott.emp table:
SELECT deptno
, ename
, sal
, comm
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME SAL COMM
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 ADAMS 1100
20 FORD 3000
20 JONES 2975
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600 300
30 BLAKE 2850
30 JAMES 950
30 MARTIN 1250 1400
30 TURNER 1500 0
30 WARD 1250 500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
` DEPTNO ENAME SAL COMM INCOME
10 CLARK 2450 2450
10 KING 5000 5000
10 MILLER 1300 1300
10 8750 8750
20 ADAMS 1100 1100
20 FORD 3000 3000
20 JONES 2975 2975
20 SCOTT 3000 3000
20 SMITH 800 800
20 10875 10875
30 ALLEN 1600 300 1900
30 BLAKE 2850 2850
30 JAMES 950 950
30 MARTIN 1250 1400 2650
30 TURNER 1500 0 1500
30 WARD 1250 500 1750
30 9400 2200 11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
SELECT deptno
, ename
, SUM (sal) AS sal
, SUM (comm) AS comm
, SUM ( sal
+ NVL (comm, 0)
) AS income
FROM scott.emp
GROUP BY GROUPING SETS ( (deptno)
, (deptno, ename)
ORDER BY deptno
, ename
;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
Added GROUPING SET example
Maybe you are looking for
-
I have a public work calendar that I wish to share with colleagues in the office. No issues for those having a Mac or an iPhone, but how can I share the calendar with Outlook for Windows users? Thanks for the help!
-
I am trying to convert a file in word file in A4 format to PDF with Acrobat.com. I noticed that the resulting PDF file is produced in Legal page size. Is there a way to change the PDF page size to A4? Thanks all for your help, Simon
-
Hi everyone, I keep getting a white line appear around images I save in Photoshop and then insert into Dreamweaver. It happens when I also save text with a transparent background. The text has a very faint white line around it. Why is this?
-
In Crytal I see parameters but the database field names are the long name ie (0CCA_C11_ZNN_0CCA_C11_Q004.M[Measures].[8WEVD1XARY9RST55SBE42RTJD3VA0MBXNGQL9Y0JC76EALK4XU]C Can someone explain how to the user friendly name ?
-
Can anybody help? I tryed upgrading to mountain lion but it wont let me and I need iPhotos urgently!