Group by and insert
drop table gtestz
create table gtestz(zip varchar2(9), tname varchar2(10));
insert into gtestz values ('11111','cnp');
insert into gtestz values('11111','onn');
insert into gtestz values('22222','cnp');
commit;
SELECT ZIP,COUNT(DISTINCT(TNAME))
FROM GTESTZ
GROUP BY ZIP ;
CREATE TABLE gtest_tar(zip varchar2(9), tname varchar2(10));
insert into gtest_tar ??On table gtestz, i am doing a unique tname check for each zip, goal is to insert only unique tnames per zip into gtest_tar
meaning, from below sql, select only those whose count = 1, and insert into gtest_tar(zip, tname), how do i do that ?
SELECT ZIP,COUNT(DISTINCT(TNAME))
FROM GTESTZ
GROUP BY ZIP ;
gtest_tar should have
zip tname
22222 cnp
Try this:
CREATE TABLE gtestz
zip VARCHAR2 (9),
tname VARCHAR2 (10)
INSERT INTO gtestz
VALUES ('11111', 'cnp');
INSERT INTO gtestz
VALUES ('11111', 'onn');
INSERT INTO gtestz
VALUES ('22222', 'cnp');
COMMIT;
SELECT * FROM GTESTZ;
SELECT ZIP, tname
FROM (SELECT ZIP,
tname,
ROW_NUMBER () OVER (PARTITION BY tname ORDER BY 1) rn
FROM GTESTZ)
WHERE rn > 1;
CREATE TABLE gtest_tar
zip VARCHAR2 (9),
tname VARCHAR2 (10)
INSERT INTO gtest_tar
SELECT ZIP, tname
FROM (SELECT ZIP,
tname,
ROW_NUMBER () OVER (PARTITION BY tname ORDER BY 1) rn
FROM GTESTZ)
WHERE rn > 1;
SELECT * FROM gtest_tar
Similar Messages
-
How to use group function in insert or update
Hai All
How can we use group function in insert or update statement
I am generating an attendance so i have different set of timing for example
0800,1200,1230, 1700 and i need to insert into these data into table with min value to intime and max value to
outtime and othere to inertval time in or out
Pls tell me with some example
For example
For INSERT
insert into T2 (barcode,empcode,intime,attend_date)
values(r2.cardn,r2.enpno,MIN(r2.ptime),r2.pdate);
For UPDATE
update dail_att set outtime= MAX(r2.ptime) where empcode=r2.enpno and barcode=r2.cardn and
attend_date=r2.pdate;
Here instead of where i need to use having so pls tell how to use
Thanks & Regards
Srikkanth.MHai Man
R2 is not a table name its a record
Let me explain clearly
I have to generate daily attendance for lot of employees So i have two table t1 and t2
T1 consist of three column empno,date,time
T2 consist of empno,name,date,intime,outtime,intrin,introut
So now i need to give the T1 Min value Of time to T2 Intime and T1 Max value of Time to T2 Outtime fields so there so many records while i am using
max(time) it gives the max value of all so i seperated by group function so now i have an error in subquery ie it is an single row subquery so i need to use multiple row subquery how i can use multiple row subquery in update statement
Thanks In Advance
Srikkanth.M -
Problem in creating group above AND group left in one report!
Hi all,
I need a report that is a combination of group above and group
left.
Suppose I have 3 table (Emp, Sales, Product):
Emp Table has 2 column
- Emp_PK
- Emp_Name
Sales Table has 4 column
-Sales_PK
-Sales_Date
-Emp_FK
-Produck_FK
-Quantity
Product Table has 3 column
-Product_PK
-Product_Name
-Product_Price
I want to make Employee Sales Report For The Month that will
look like this:
Emp Number___: Emp_PK
Emp Name_____: Emp_Name
Sales Date______Product_Name____Quantity \(2 sales
________________Product_Name____Quantity /the date)
Sales_Date______Product_Name____Quantity
As you can see this consist of group above (The Employee) and
group left (The Sales and Product).
I create this by using 2 queries and link them (the Emp_PK from
1st query and Emp_FK from 2nd query) on the report builder using
data link.
The first query is:
Select Emp_PK, Emp_Name from Emp
The second query is
Select Emp_FK, Sales_Date, Product_Name, Quantity
From Sales, Product
Where Product_PK=PRODUCT_FK
I then create the layout for second query and choose group left
for Sales_Date using wizard and I create additional layout to
for the employee.
The problem is that when I run this report, it will print ALL
the employee record first (including employee who has NOT sale
anything) and then on the last page it will print the record of
Last employee on the Emp table and ALL sales record (including
those that is done by other employee).
This report will run correctly if I choose an exact employee
(For example by adding Where Emp_PK=1111 in the first query) to
report all of the sales done by this person (employee with emp
number of 1111). However I need the report to run and print
ONLY those employee who has Sales Records!
I thought that by linking the 2 queries in Data Model, it will
have the same effect as linking using the WHERE clause in query.
If suppose I create a query like this:
SELECT Emp_PK, Emp_Name, Sales_Date, Product_Name, Quantity
FROM Emp, Sales, Product
WHERE Emp_PK=Emp_FK AND Product_PK=Product_FK
The report will run OK but I can only choose EITHER group above
or group left for this ONE query methods in report Wizard.
Sorry if it is a long question but I hope you can see what I am
trying to do.
Thanks in advance for any tip.hello,
of course you can create group left and group above blocks in a
single report.
you might want to use the INSERT REPORT BLOCK instead of the
report wizard, as the report wizard only allows you to use one
report layout per report, where the report block wizard (invoked
by INSERT REPORT BLOCK) allows you to choose on a per-block
basis.
of course you can create the blocks completely from scarth by
hand, if you want to.
regards,
the oracle reports team --pw -
Compare String in a table and insert the common values into a New table
Hi all,
Anyone has idea on how to compare a string value in a table.
I have a Students Table with Student_id and Student_Subject_list columns as below.
create table Students( Student_id number,
Student_Subject_list varchar2(2000)
INSERT INTO Students VALUES (1,'Math,Science,Arts,Music,Computers,Law,Business,Social,Language arts,History');
INSERT INTO Students VALUES (2,'Math,Law,Business,Social,Language arts,History,Biotechnology,communication');
INSERT INTO Students VALUES (3,'History,Spanish,French,Langage arts');
INSERT INTO Students VALUES (4,'History,Maths,Science,Chemistry,English,Reading');
INSERT INTO Students VALUES (5,'Math,Science,Arts,Music,Computer Programming,Language arts,History');
INSERT INTO Students VALUES (6,'Finance,Stocks');
output
Student_id Student_Subject_list
1 Math,Science,Arts,Music,Computers,Law,Business,Social,Language arts,History
2 Math,Law,Business,Social,Language arts,History,Biotechnology,communication
3 History,Spanish,French,Langage arts
4 History,Maths,Science,Chemistry,English,Reading
5 Math,Science,Arts,Music,Computer Programming,Language arts,History
6 Finance,Stocks
I need help or some suggestion in write a query which can compare each row string value of Student_Subject_list columns and insert the
common subjects into a new table(Matched_Subjects).The second table should have the below colums and data.
create table Matched_Subjects(Student_id number,
Matching_studesnt_id Number,
Matched_Student_Subject varchar2(2000)
INSERT INTO Matched_Subjects VALUES (1,2,'Math,Law,Business,Social,Language arts,History');
INSERT INTO Matched_Subjects VALUES (1,3,'History,Langage arts');
INSERT INTO Matched_Subjects VALUES (1,4,'History,Maths,Science');
INSERT INTO Matched_Subjects VALUES (1,5,'Math,Science,Arts,Music,Language arts,History');
INSERT INTO Matched_Subjects VALUES (2,3,'History,Langage arts');
INSERT INTO Matched_Subjects VALUES (2,4,'History,Maths');
INSERT INTO Matched_Subjects VALUES (2,5,'Math,Language arts,History');
INSERT INTO Matched_Subjects VALUES (3,4,'History');
INSERT INTO Matched_Subjects VALUES (3,5,'Language arts,History');
INSERT INTO Matched_Subjects VALUES (4,5,'Math,Science');
output:
Student_id Match_Student_id Matched_Student_Subject
1 2 Math,Law,Business,Social,Language arts,History
1 3 History,Langage arts
1 4 History,Maths,Science
1 5 Math,Science,Arts,Music,Language arts,History
2 3 History,Langage arts
2 4 History,Maths
2 5 Math,Language arts,History
3 4 History
3 5 Language arts,History
4 5 Math,Science
any help will be appreciated.
Thanks.
Edited by: user7988 on Sep 25, 2011 8:45 AMuser7988 wrote:
Is there an alternate approach to this without using xmlagg/xmlelement What Oracle version are you using? In 11.2 you can use LISTAGG:
insert
into Matched_Subjects
with t as (
select student_id,
column_value l,
regexp_substr(student_subject_list,'[^,]+',1,column_value) subject
from students,
table(
cast(
multiset(
select level
from dual
connect by level <= length(regexp_replace(student_subject_list || ',','[^,]'))
as sys.OdciNumberList
select t1.student_id,
t2.student_id,
listagg(t1.subject,',') within group(order by t1.l)
from t t1,
t t2
where t1.student_id < t2.student_id
and t1.subject = t2.subject
group by t1.student_id,
t2.student_id
STUDENT_ID MATCHING_STUDESNT_ID MATCHED_STUDENT_SUBJECT
1 2 Math,Law,Business,Social,Language arts,History
1 3 Language arts,History
1 4 Science,History
1 5 Math,Science,Arts,Music,Language arts,History
2 3 Language arts,History
2 4 History
2 5 Math,Language arts,History
3 4 History
3 5 History,Language arts
4 5 History,Science
10 rows selected.
SQL> Prior to 11.2 you can create your own string aggregation function STRAGG - there are plenty of example on this forum. Or use hierarchical query:
insert
into Matched_Subjects
with t1 as (
select student_id,
column_value l,
regexp_substr(student_subject_list,'[^,]+',1,column_value) subject
from students,
table(
cast(
multiset(
select level
from dual
connect by level <= length(regexp_replace(student_subject_list || ',','[^,]'))
as sys.OdciNumberList
t2 as (
select t1.student_id student_id1,
t2.student_id student_id2,
t1.subject,
row_number() over(partition by t1.student_id,t2.student_id order by t1.l) rn
from t1,
t1 t2
where t1.student_id < t2.student_id
and t1.subject = t2.subject
select student_id1,
student_id2,
ltrim(sys_connect_by_path(subject,','),',') MATCHED_STUDENT_SUBJECT
from t2
where connect_by_isleaf = 1
start with rn = 1
connect by student_id1 = prior student_id1
and student_id2 = prior student_id2
and rn = prior rn + 1
STUDENT_ID MATCHING_STUDESNT_ID MATCHED_STUDENT_SUBJECT
1 2 Math,Law,Business,Social,Language arts,History
1 3 Language arts,History
1 4 Science,History
1 5 Math,Science,Arts,Music,Language arts,History
2 3 Language arts,History
2 4 History
2 5 Math,Language arts,History
3 4 History
3 5 History,Language arts
4 5 History,Science
10 rows selected.SY. -
Group image and text in pages grayed out
group image and text in pages grayed out... any help please?
They both have to be free floating objects ie an image/shape/table/chart/textbox not inserted in the text.
Peter -
Difference in number of records in GROUP BY and PARTITION BY
Hi Experts
If I run the following query I got 997 records by using GROUP BY.
SELECT c.ins_no, b.pd_date,a.project_id,
a.tech_no
FROM mis.tranche_balance a,
FMSRPT.fund_reporting_period b,
ods.proj_info_lookup c,
ods.institution d
WHERE a.su_date = b.pd_date
AND a.project_id = c.project_id
AND c.ins_no = d.ins_no
AND d.sif_code LIKE 'P%'
AND d.sif_code <> 'P-DA'
AND a.date_stamp >='01-JAN-2011'
AND pd_date='31-MAR-2011'
GROUP BY c.ins_no,
b.pd_date,
a.project_id,
a.tech_no;
I want to show the extra columns a.date_stamp and a.su_date
in the out put so that I have used PARTITION BY in the second query but I got 1079 records.
SELECT c.ins_no, b.pd_date,a.date_stamp,a.su_date, a.project_id,
a.tech_no,
COUNT(*) OVER(PARTITION BY c.ins_no,
b.pd_date,
a.project_id,
a.tech_no)c
FROM mis.tranche_balance a,
FMSRPT.fund_reporting_period b,
ods.proj_info_lookup c,
ods.institution d
WHERE a.su_date = b.pd_date
AND a.project_id = c.project_id
AND c.ins_no = d.ins_no
AND d.sif_code LIKE 'P%'
AND d.sif_code <> 'P-DA'
AND a.date_stamp >='01-JAN-2011'
AND pd_date='31-MAR-2011'
Please help me why I got 1079 records.
And also please help me how to show the two extra columns in the out put whcich are not used in
GROUP BY clause.
Thanks in advance.Hi,
user9077483 wrote:
Hi Experts
If I run the following query I got 997 records by using GROUP BY. ...Let''s call this "Query 1", and the number of rows it returns "N1".
The results tell you that there are 997 distinct combinations of the GROUP BY columns (c.ins_no, b.pd_date, a.project_id, a.tech_no).
I want to show the extra columns a.date_stamp and a.su_date
in the out put so that I have used PARTITION BY in the second query but I got 1079 records. ...Let's call the query without the GROUP BY "Query 2", and the number of rows it returns "N2".
Please help me why I got 1079 records.Because there are 1079 rows that meet all the GROUP BY conditions. Query 2 has nothing to with distinct values in any columns. You would expect that N2 to be at least as high as N1, but it's not surprising that the N2 is higher than N1.
And also please help me how to show the two extra columns in the out put whcich are not used in
GROUP BY clause.Doesn't Query 2 show those two columns already? If the Query 2 is not producing the results you want, then what results do you want?
Post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Explain, using specific examples, how you get those results from that data. Point out a couple of places where Query 2 is not doing what you want.
Always say which version of Oracle you're using. -
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 -
Can not Group text and shape/object
I have previously made frequent use of grouping text and objects or images together. But in Keynote 4.0.2 this is not possible (for me at least). I am able to lock multiple images, but the group, mask and alpha buttons are not active when selecting a combination of the two (text and objects). Images or objects can be grouped together. Is this a bug or what ?
Open a NEW presentation (it should default to the Title and Subtitle slide of the theme)
Type some text into the Title
Insert a shape (square)
Select the shape and the Title
You should see that you cannot group anything with either the Title or Subtitle object of a slide. If you want to group text to an object, you have to create a new text object. Would this describe your inability to group (ie. limited to when you have Title/Subtitle selected?) -
How to "group by" and use functions on grouped records
I group rows and wantto select the max date row in date column. The other columns can include same data in its rows, thus i wantto select distinct data in the rows. I use the following query, but ir throws the message "ORA-00936: missing expression."
select max(t2.tarih), distinct (t1.ihlkodu),distinct(t1.ihlaltktgkodu), distinct(t1.kuladi),distinct(t4.ad) from ihale_katilimcilar t1, ihale_hareket t2, ihale_sirket t4
where t1.id_iliski=t2.id_iliski and t1.kuladi=t4.kullaniciadi and t1.ihlkodu=145 and t1.ihlaltktgkodu=135 and t1.aktif=1
group by t2.tarih, t1.ihlkodu,t1.ihlaltktgkodu,t1.kuladi,t4.ad
Here t2.tarih is a field of date and i wantto select the max of this.
t1.ihlkodu has all the same data in its rows.
t1.ihlaltktgkodu too has all the same data in its rows.
t1.kuladi may have ,let me say, 5 rows of same data and 6 rows of another same data in this 6 but different then the first 5 rows of same data. That is, the content of the 6 and 5 is the same in 6 and 5 but different then each other.
and finally[b] t4.ad too may have ,let me say, 5 rows of same data and 6 rows of another same data in this 6 but different then the first 5 rows of same data.(That is, the content of the 6 and 5 is the same in 6 and 5 but different then each other)
How could i group them?Here is the script of tables:
-- Create table
create table IHALE_SIRKET
SRKTKODU NUMBER not null,
AD VARCHAR2(30) not null,
ADRES VARCHAR2(50),
TEL1 VARCHAR2(15),
TEL2 VARCHAR2(15),
FAX VARCHAR2(15),
EMAIL VARCHAR2(20),
KARALISTE NUMBER default -1,
AKTIF NUMBER(1) default -1,
SICILNO VARCHAR2(20) not null,
VERGINO VARCHAR2(20) not null,
TICSICILGAZSAYI VARCHAR2(10) not null,
TICSICILGAZTARIH DATE not null,
ODASICILNO VARCHAR2(20),
TESCILTARIHI DATE,
SERMAYE VARCHAR2(20),
DERECE NUMBER(2),
ODAKAYITTARIHI DATE,
KULLANICIADI VARCHAR2(15)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
-- Create/Recreate primary, unique and foreign key constraints
alter table IHALE_SIRKET
add constraint CONSTRAINT_SRKTKODUPK primary key (SRKTKODU);
-- Create/Recreate indexes
create unique index IHALE_SIRKET_SRKTKODU on IHALE_SIRKET (SRKTKODU)
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
-- Create table
create table IHALE_KATILIMCILAR
KULADI VARCHAR2(20),
SONUC NUMBER(1),
AKTIF NUMBER(1) default 1,
SRKTKODU VARCHAR2(10) not null,
SONBULUNMAZAMANI DATE default sysdate,
SIRA NUMBER(1) default 0,
EKSURETALEP VARCHAR2(50),
ID NUMBER(6) not null,
IHLKODU NUMBER not null,
IHLALTKTGKODU VARCHAR2(10) not null,
ID_ILISKI NUMBER
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
-- Create/Recreate primary, unique and foreign key constraints
alter table IHALE_KATILIMCILAR
add constraint CONSTRAINT_IHLKTLMIDPK primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
-- -- -- Create table
create table IHALE_HAREKET
ID_ILISKI NUMBER not null,
TEKLIF VARCHAR2(15) not null,
TARIH DATE default sysdate,
ID NUMBER not null
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
-- Create/Recreate primary, unique and foreign key constraints
alter table IHALE_HAREKET
add constraint CONSTRAINT_IHLHAREKETPK primary key (ID)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
initial 64K
minextents 1
maxextents unlimited
Here is the content of those tables:
prompt Loading IHALE_HAREKET...
insert into IHALE_HAREKET (ID_ILISKI, TEKLIF, TARIH, ID)
values (189, '1400YTL', to_date('12-02-2008 14:35:07', 'dd-mm-yyyy hh24:mi:ss'), 1);
insert into IHALE_HAREKET (ID_ILISKI, TEKLIF, TARIH, ID)
values (203, '1200YTL', to_date('12-02-2008 16:03:16', 'dd-mm-yyyy hh24:mi:ss'), 2);
insert into IHALE_HAREKET (ID_ILISKI, TEKLIF, TARIH, ID)
values (203, '1100YTL', to_date('12-02-2008 16:03:16', 'dd-mm-yyyy hh24:mi:ss'), 3);
insert into IHALE_HAREKET (ID_ILISKI, TEKLIF, TARIH, ID)
values (189, '1500 YTL', to_date('12-02-2008 14:34:30', 'dd-mm-yyyy hh24:mi:ss'), 0);
prompt 4 records loaded
prompt Loading IHALE_KATILIMCILAR...
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '42', to_date('12-02-2008 13:33:32', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 63, 141, '134', 191);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '46', to_date('12-02-2008 13:33:32', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 64, 141, '134', 192);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values ('KEM.ESM', null, 1, '44', to_date('12-02-2008 11:00:41', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 61, 145, '135', 189);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '45', to_date('12-02-2008 13:33:42', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 69, 141, '133', 197);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '42', to_date('12-02-2008 13:33:36', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 65, 141, '132', 193);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '45', to_date('12-02-2008 13:33:36', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 66, 141, '132', 194);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '46', to_date('12-02-2008 13:33:36', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 67, 141, '132', 195);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '42', to_date('12-02-2008 13:33:42', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 68, 141, '133', 196);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '44', to_date('12-02-2008 13:34:23', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 70, 142, '252', 198);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '45', to_date('12-02-2008 13:34:23', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 71, 142, '252', 199);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '44', to_date('12-02-2008 13:34:40', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 72, 143, '253', 200);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '46', to_date('12-02-2008 13:34:40', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 73, 143, '253', 201);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '45', to_date('12-02-2008 11:00:38', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 60, 145, '136', 188);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values (null, null, 0, '44', to_date('12-02-2008 15:59:21', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 74, 145, '136', 202);
insert into IHALE_KATILIMCILAR (KULADI, SONUC, AKTIF, SRKTKODU, SONBULUNMAZAMANI, SIRA, EKSURETALEP, ID, IHLKODU, IHLALTKTGKODU, ID_ILISKI)
values ('KE.ES', null, 1, '45', to_date('12-02-2008 15:59:25', 'dd-mm-yyyy hh24:mi:ss'), 0, null, 75, 145, '135', 203);
commit;
prompt 15 records loaded
prompt Loading IHALE_SIRKET...
insert into IHALE_SIRKET (SRKTKODU, AD, ADRES, TEL1, TEL2, FAX, EMAIL, KARALISTE, AKTIF, SICILNO, VERGINO, TICSICILGAZSAYI, TICSICILGAZTARIH, ODASICILNO, TESCILTARIHI, SERMAYE, DERECE, ODAKAYITTARIHI, KULLANICIADI)
values (42, 'KEMMM', 'asddd', '03123456444', '03123456444', '03123456444', '[email protected]', 0, 1, '325999444', '234999444', '34599944', to_date('04-02-2008', 'dd-mm-yyyy'), '23/29444', to_date('04-02-2008', 'dd-mm-yyyy'), '4.000.000.11YTL', 1, to_date('04-02-2008', 'dd-mm-yyyy'), null);
insert into IHALE_SIRKET (SRKTKODU, AD, ADRES, TEL1, TEL2, FAX, EMAIL, KARALISTE, AKTIF, SICILNO, VERGINO, TICSICILGAZSAYI, TICSICILGAZTARIH, ODASICILNO, TESCILTARIHI, SERMAYE, DERECE, ODAKAYITTARIHI, KULLANICIADI)
values (46, 'MLK', 'fgh', '456', '456', '456', '[email protected]', 0, 1, '2346', '2346', '2346', to_date('27-01-2008', 'dd-mm-yyyy'), '2346', to_date('25-01-2008', 'dd-mm-yyyy'), '2346', 1, to_date('22-01-2008', 'dd-mm-yyyy'), null);
insert into IHALE_SIRKET (SRKTKODU, AD, ADRES, TEL1, TEL2, FAX, EMAIL, KARALISTE, AKTIF, SICILNO, VERGINO, TICSICILGAZSAYI, TICSICILGAZTARIH, ODASICILNO, TESCILTARIHI, SERMAYE, DERECE, ODAKAYITTARIHI, KULLANICIADI)
values (44, 'ASD', 'asd', '123', '123', '123', '[email protected]', 0, 1, '123', '123', '123', to_date('10-01-2008', 'dd-mm-yyyy'), '123', to_date('17-01-2008', 'dd-mm-yyyy'), '123', 1, to_date('11-01-2008', 'dd-mm-yyyy'), 'KEM.ESM');
insert into IHALE_SIRKET (SRKTKODU, AD, ADRES, TEL1, TEL2, FAX, EMAIL, KARALISTE, AKTIF, SICILNO, VERGINO, TICSICILGAZSAYI, TICSICILGAZTARIH, ODASICILNO, TESCILTARIHI, SERMAYE, DERECE, ODAKAYITTARIHI, KULLANICIADI)
values (45, 'JKL', 'jkl', '234', '234', '345', '[email protected]', 0, 1, '234', '234', '234', to_date('04-01-2008', 'dd-mm-yyyy'), '234', to_date('27-01-2008', 'dd-mm-yyyy'), '234', 2, to_date('19-01-2008', 'dd-mm-yyyy'), 'KE.ES');
When i use the following sql:
select t2.teklif, t2.tarih, t1.ihlkodu, t1.ihlaltktgkodu, t1.kuladi,t4.ad from ihale_katilimcilar t1, ihale_hareket t2, ihale_sirket t4
where t1.id_iliski=t2.id_iliski and t1.kuladi=t4.kullaniciadi and t1.ihlkodu=145 and t1.ihlaltktgkodu=135 and t1.aktif=1
group by t2.teklif, t2.tarih, t1.ihlkodu,t1.ihlaltktgkodu,t1.kuladi,t4.ad
The result i get is:
1100YTL 12.02.2008 16:08:16 145 135 KE.ES JKL ***
1200YTL 12.02.2008 16:03:16 145 135 KE.ES JKL
1400YTL 12.02.2008 14:35:07 145 135 KEM.ESM ASD ***
1500 YTL 12.02.2008 14:34:30 145 135 KEM.ESM ASD
The one i wantto get is the rows of the latest date in each group:
1100YTL 12.02.2008 16:08:16 145 135 KE.ES JKL [b]***
1400YTL 12.02.2008 14:35:07 145 135 KEM.ESM ASD ***
max date -->latest date , most up to date
Message was edited by:
user611878
Message was edited by:
kem06.ora -
Sqlserver query using Group by and Order by
SUM(BILL_DETAIL.x_bill_quantity) as BILL_QUANTITY,
MIN(BILL_DETAIL.x_billable_to) as BILLABLE_TO,
MIN(BILL_DETAIL.x_billable_yn) as BILLABLE_YN,
AVG(BILL_DETAIL.x_bill_rate) as BILL_RATE,
MIN(BILL_DETAIL.x_cost_rate) as COST_RATE,
MIN(BILL_DETAIL.x_cost_total) as COST_TYPE,
LISTAGG(BILL_DETAIL.objid, ',') WITHIN GROUP(ORDER BY BILL_DETAIL.objid) as ID_LIST
FROM table_x_gsa_bill_detail BILL_DETAIL
WHERE (1=1)
GROUP BY (DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO || ',' || DETAIL_CLASS || ',' || COST_TYPE || ',' || BILL_RATE)
ORDER BY DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO || ',' || DETAIL_CLASS ||
) dt WHERE rn BETWEEN 0 AND 1
Can any one pls help me using of Case Condition keyword instead of Decode in the above query ??? iam not able to convert above query for group by and order by..
Actually i need to do group by the aggragate values which i got the values from the fields of BILLABLE_YN,BILLABLE_TO,DETAIL_CLASS, COST_TYPE, BILL_RATE.
where as in oracle i can run above query using decode keyword where as in sqlserver iam not able to use BILLABLE_YN field alias of above query in group by .
i tried like by using following way but it is wrong because here iam not using aggragate values of fields in group by funtion please help me in converting query in sqlserver. GROUP BY (case BILLABLE_YN when 1 then 'Billable' when 0 then 'Non-Billable' else
'Non-Billable' End BILLABLE_YN + ',' + BILLABLE_TO + ',' + DETAIL_CLASS + ',' + COST_TYPE + ',' + BILL_RATE)
KrishnaCREATE TABLE DETAIL
([objid] int,[x_billable_to] varchar(19), [x_bill_quantity] int,
[x_billable_yn] int, [x_bill_rate] int, [COST_TYPE] varchar(19) )
INSERT INTO
DETAIL
([objid], [x_billable_to], [x_bill_quantity], [x_billable_yn], [x_bill_rate],[COST_TYPE])
VALUES
(1, 'Customer', 3, 1, 20,'Parking'),
(2, 'Customer', 1, 1, 25,'Toll'),
(3, 'Customer', 2, 1, 20,'Parking')
Pls convert following query for executing query in sqlserver ..for the column ID_List it should return data like 1,2,3
SELECT * FROM (SELECT 1 rn,
SUM(BILL_DETAIL.x_bill_quantity) as BILL_QUANTITY,
MIN(BILL_DETAIL.x_billable_to) as BILLABLE_TO,
MIN(BILL_DETAIL.x_billable_yn) as BILLABLE_YN,
AVG(BILL_DETAIL.x_bill_rate) as BILL_RATE,
LISTAGG(BILL_DETAIL.objid, ',') WITHIN GROUP(ORDER BY BILL_DETAIL.objid) as ID_LIST
FROM BILL_DETAIL
WHERE (1=1)
GROUP BY (DECODE(x_billable_yn, 1, 'Billable', 'Non-Billable') + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate)
ORDER BY DECODE(x_billable_yn, 1, 'Billable', 'Non-Billable') + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate
)dt
WHERE rn BETWEEN 0 AND 1
Krishna
sounds like this
SELECT *
FROM
SELECT 1 rn,
SUM(BILL_DETAIL.x_bill_quantity) as BILL_QUANTITY,
MIN(BILL_DETAIL.x_billable_to) as BILLABLE_TO,
MIN(BILL_DETAIL.x_billable_yn) as BILLABLE_YN,
AVG(BILL_DETAIL.x_bill_rate) as BILL_RATE,
LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1) AS ID_Listing
FROM BILL_DETAIL bd
CROSS APPLY (
SELECT BILL_DETAIL.objid + ',' AS [text()]
FROM BILL_DETAIL
WHERE objid = bd.objid
FOR XML PATH('')
)bd1(ID_LIST)
WHERE (1=1)
GROUP BY (CASE WHEN x_billable_yn = 1 THEN 'Billable' ELSE 'Non-Billable'END + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate),
LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1)
ORDER BY (CASE WHEN x_billable_yn = 1 THEN 'Billable' ELSE 'Non-Billable'END + ',' + x_billable_to + ',' + COST_TYPE + ',' + x_bill_rate),
LEFT(bd1.ID_LIST,LEN(bd1.ID_LIST)-1)
)dt
WHERE rn BETWEEN 0 AND 1
Please Mark This As Answer if it solved your issue
Please Vote This As Helpful if it helps to solve your issue
Visakh
My Wiki User Page
My MSDN Page
My Personal Blog
My Facebook Page -
Group by and record count simplification, try #2
I know what I’m trying to do, not sure how to get there. I am providing the make table and inserts along with the query that doesn’t work.
/*table*/
CREATE TABLE claims_step_table (
table_id INTEGER PRIMARY KEY,
record_id NUMBER,
step_code VARCHAR2(20 Byte),
date_completed DATE,
step_date DATE
/*inserts*/
INSERT INTO claims_step_table VALUES (1, 123456,'P96','10-JAN-09','05-JAN-09');
INSERT INTO claims_step_table VALUES (2, 123456,'L61',null,'05-JAN-09');
INSERT INTO claims_step_table VALUES (3, 67,'P96','10-MAR-08','05-MAR-08');
INSERT INTO claims_step_table VALUES (4, 67,'L61',null,'05-MAR-08');
INSERT INTO claims_step_table VALUES (5, 67,'U18',null,'05-MAR-08');
INSERT INTO claims_step_table VALUES (6, 67,'429',null,'05-MAR-08');
INSERT INTO claims_step_table VALUES (7, 9876,'L61',null,'05-FEB-08');
INSERT INTO claims_step_table VALUES (8, 9876,'429',null,'05-FEB-08');
INSERT INTO claims_step_table VALUES (9, 123456,'P96','10-AUG-07','05-JUN-07');
INSERT INTO claims_step_table VALUES (10, 123456,'L61',null,'05-JUN-07');
INSERT INTO claims_step_table VALUES (11, 123456,'U18',null,'05-JUN-07');
INSERT INTO claims_step_table VALUES (12, 123456,'429',null,'05-JUN-07');
INSERT INTO claims_step_table VALUES (13, 67555,'L61',null,'07-NOV-08');
INSERT INTO claims_step_table VALUES (14, 67555,'P96','08-NOV-08','07-NOV-08');
INSERT INTO claims_step_table VALUES (15, 67555,'429','15-NOV-08','07-NOV-08');
COMMIT;
/*query*/
SELECT
RECORD_ID,
max(STEP_DATE)
from(
select
RECORD_ID,
STEP_DATE,
case
when STEP_CODE = 'L61' then DATE_COMPLETED
end as STEP_L61,
case
when STEP_CODE = 'P96' then DATE_COMPLETED
end as STEP_P96,
case
when STEP_CODE = 'U18' then DATE_COMPLETED
end as STEP_U18,
case
when STEP_CODE = '429' then DATE_COMPLETED
end as STEP_429
from
CLAIMS_STEP_TABLE
where
STEP_CODE in('L61','P96','U18','429')
where
STEP_L61 is null
and
STEP_P96 is not null
and
STEP_U18 is null
and
STEP_429 is null
group by RECORD_ID, STEP_DATE
order by RECORD_ID, STEP_DATE DESCWhat I need is all the RECORD_ID’s and STEP_DATE’s where
• STEP_CODE’s L61, U18 and 429 are null AND STEP_CODE P96 is completed
• Only the newest records based on the STEP_DATE(so the max step_date), if multiple RECORD_ID's.
The query should return *2* tuples
RECORD_ID MAX(STEP_DATE)
67 03/05/2008
123456 01/05/2009I currently get the following
RECORD_ID MAX(STEP_DATE)
67 03/05/2008
67555 11/07/2008 <= step 429 not null
123456 01/05/2009
123456 06/05/2007 <= old record need newestThis is a much more simplified query than the original as there are many table joins. There are 100k records + in the real CLAIMS_STEP_TABLE with over 1k different STEP_CODE’s. (this is dummy table for this example). BTW on the real DB i only have read access.
Thanks for your patience and understanding with a noob, hope this attempt is clearer.The reason it's failing is because your pivot (inner query) is returning sparse results:
RECORD_ID STEP_DATE STEP_L61 STEP_P96 STEP_U18 STEP_429
123456 05-JAN-09 10-JAN-09
123456 05-JAN-09
67 05-MAR-08 10-MAR-08
67 05-MAR-08
67 05-MAR-08
67 05-MAR-08
9876 05-FEB-08
9876 05-FEB-08
123456 05-JUN-07 10-AUG-07
123456 05-JUN-07
123456 05-JUN-07
123456 05-JUN-07
67555 07-NOV-08
67555 07-NOV-08 08-NOV-08
67555 07-NOV-08 15-NOV-08So in the case of 67555 there is a situation where all the conditions of the outer query are met. What you need to do is remove the extra NULLs like so:
SELECT RECORD_ID
, STEP_DATE
, MAX(CASE
WHEN STEP_CODE = 'L61' THEN DATE_COMPLETED
END) AS STEP_L61,
MAX(CASE
WHEN STEP_CODE = 'P96' THEN DATE_COMPLETED
END) AS STEP_P96,
MAX(CASE
WHEN STEP_CODE = 'U18' THEN DATE_COMPLETED
END) AS STEP_U18,
MAX(CASE
WHEN STEP_CODE = '429' THEN DATE_COMPLETED
END) AS STEP_429
FROM CLAIMS_STEP_TABLE
WHERE STEP_CODE IN ('L61','P96','U18','429')
GROUP BY RECORD_ID
, STEP_DATETo get this result:
RECORD_ID STEP_DATE STEP_L61 STEP_P96 STEP_U18 STEP_429
67555 07-NOV-08 08-NOV-08 15-NOV-08
9876 05-FEB-08
123456 05-JUN-07 10-AUG-07
67 05-MAR-08 10-MAR-08
123456 05-JAN-09 10-JAN-09Then your whole query returns the following:
SQL> SELECT RECORD_ID
2 , MAX(STEP_DATE)
3 FROM
4 (
5 SELECT RECORD_ID
6 , STEP_DATE
7 , MAX(CASE
8 WHEN STEP_CODE = 'L61' THEN DATE_COMPLETED
9 END) AS STEP_L61,
10 MAX(CASE
11 WHEN STEP_CODE = 'P96' THEN DATE_COMPLETED
12 END) AS STEP_P96,
13 MAX(CASE
14 WHEN STEP_CODE = 'U18' THEN DATE_COMPLETED
15 END) AS STEP_U18,
16 MAX(CASE
17 WHEN STEP_CODE = '429' THEN DATE_COMPLETED
18 END) AS STEP_429
19 FROM CLAIMS_STEP_TABLE
20 WHERE STEP_CODE IN ('L61','P96','U18','429')
21 GROUP BY RECORD_ID
22 , STEP_DATE
23 )
24 WHERE STEP_L61 IS NULL
25 AND STEP_P96 IS NOT NULL
26 AND STEP_U18 IS NULL
27 AND STEP_429 IS NULL
28 GROUP BY RECORD_ID
29 /
RECORD_ID MAX(STEP_
123456 05-JAN-09
67 05-MAR-08
SQL>HTH! -
HT2486 since downloading mavericks my smart groups don't insert in mails.
since downloading mavericks my smart groups don't insert in mails.
Hi Colin
I dont know if this fixes your problem, but I found this article: http://www.macosxhints.com/article.php?story=20050616151738798
The main suggestion is this:
I was able to get around it in a simple but possibly not obvious way. First, make a smart group with your wanted criteria. Next make a regular group whose only member is the smart group. Presto! A smart group that you can use in Mail.app, and that will also auto-complete.
Will -
Data from table in xml Format and Inserting it into Table
Hi All
I have table where xml data is stored in long format with xml tag know i have read the entire xml xoulmn which is xml tag and insert it into diffrent table can any suggest me the code
Thanks & RegardsI believe you are on the wrong forum. You want the XML DB forum.
See:
XML DB -
I need to show grouped id and only the max order value for each unique id
select distinct
Table1.id,
Table1.id +' - '+ Table1.VisitNumber +' : '+ Table1.Priority as UidVisitKey,
Table1.VisitNumber,
DATEDIFF(d, [dob],[Visite_dte])/365.25 as Age_On_Visit,
Table1.Priority,
Table1.OrderOfVisit,
Table1.OrderOfVisit + ' - ' + Table1.Notes AS VisitNote,
Table1.Visitor_FName,
Table1.Visitor_SName,
Table2.dob,
Table2.sex,
Table1.Visit_dte,
into #Temp1
FROM Table1 INNER JOIN
Table2 ON Table1.id = Table2.id
WHERE Table1.LeaveDate IS NOT NULL
and Table1.LeaveDate between DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))
and DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))
select #Temp1.id, max(#Temp1.[OrderOfVisit]), #Temp1.VisitNote
from #Temp1
group by #Temp1.id, #Temp1.OrderOfVisit, #Temp1.[VisitNote]
ORDER BY #Temp1.id
drop table #Temp1
---I need to show grouped id and only the max OrderOfVisit for each unique id, and the VisitNote for each OrderOfVisit
----------------need help-------------Sounds like this
select distinct
Table1.id,
Table1.id +' - '+ Table1.VisitNumber +' : '+ Table1.Priority as UidVisitKey,
Table1.VisitNumber,
DATEDIFF(d, [dob],[Visite_dte])/365.25 as Age_On_Visit,
Table1.Priority,
Table1.OrderOfVisit,
Table1.OrderOfVisit + ' - ' + Table1.Notes AS VisitNote,
Table1.Visitor_FName,
Table1.Visitor_SName,
Table2.dob,
Table2.sex,
Table1.Visit_dte,
into #Temp1
FROM Table1 INNER JOIN
Table2 ON Table1.id = Table2.id
WHERE Table1.LeaveDate IS NOT NULL
and Table1.LeaveDate between DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0))
and DATEADD(ms,-3,DATEADD(mm,0,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)))
select id,OrderOfVisit,VisitNote
from
select #Temp1.id, #Temp1.[OrderOfVisit], #Temp1.VisitNote,ROW_NUMBER() OVER (PARTITION BY #Temp1.id ORDER BY #Temp1.[OrderOfVisit] DESC) AS Seq
from #Temp1
)t
WHERE Seq = 1
ORDER BY id
drop table #Temp1
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Associative array comparison and INSERT upon IF condition
Hi Guys,
I have written this pl sql code to identify non existing sellers and insert their sales channel information into the dimension table (dimensional table update).
Somehow,......nothing is inserted and this script runs for 12 hours+ without any result. the sql autotrace shows no result and the explain plan (button on sql developer throws upon clicking "missing keyword". I have no
information what is going on/wrong. Does anyone spot an error?
UNDEFINE DimSales;
UNDEFINE FactTable;
DEFINE DimSales = 'testsales';
DEFINE FactTable = 'testfact';
DECLARE
v_SellerNo VarChar(9);
v_error_code T_ERRORS.v_error_code%TYPE;
v_error_message T_ERRORS.v_error_message%TYPE;
TYPE assoc_array_str_type1 IS TABLE OF VARCHAR2(32) INDEX BY PLS_INTEGER;
v1 assoc_array_str_type1;
TYPE assoc_array_str_type2 IS TABLE OF VARCHAR2(32) INDEX BY PLS_INTEGER;
v2 assoc_array_str_type2;
BEGIN
--Collect all distinct SellerNo into associative array (hash table)
select distinct SellerNo bulk collect into v1 from &FactTable;
select distinct seller_id bulk collect into v2 from &DimSales;
v_SellerNo := v1.first;
loop
exit when v1 is null;
--1 Check if v_SellerNo already exists in DIM_Sales (if NOT/FALSE, its a new seller and we can insert all records for that seller
if (v2.exists(v_SellerNo)=false) THEN
INSERT INTO &DimSales (K_Sales,REG,BVL,DS, VS,RS,GS,VK)
(SELECT DISTINCT trim(leading '0' from RS||GS) ,REG BVL,DS,VS,RS,GS,VK from &FactTable where SellerNo =v_SellerNo);
--ELSE
end if;
v_SellerNo := v1.next(v_SellerNo);
end loop;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
--v_error_code := SQLCODE
--v_error_message := SQLERRM
--INSERT INTO t_errors VALUES ( v_error_code, v_error_message);
END;
---------------------------------------------------------------Distinct clause requires a sort. Sorts can be very expensive.
Bulk collects that are not constrained in fetch size, can potentially fetch millions of rows - requiring that data to be wholly read into server memory. I have seen how this can degrade performance so badly that the kernel reboots the server.
Using PL/SQL loops to process and insert/update/delete data is often problematic due to its row-by-row approach - also called slow-by-slow approach. It is far more scalable letting SQL do the "loop" processing, by using joins, sub-selects and so on.
Where the conditional processing is too complex for SQL to handle, then PL/SQL is obviously an alternative to use. Ideally one should process data sets as oppose to rows in PL//SQL. Reduce context switching by using bulk fetches and bulk binds.
But PL/SQL cannot execute in parallel as the SQL it fires off can. If after all the optimisation, the PL/SQL process still needs to hit a million rows to process, it will be slow irrespective of how optimal that PL/SQL approach and design - simply because of the number of rows and the processing overheads per row.
In that case, the PL/SQL code itself need to be parallelised. There are a number of ways to approach this problem - the typical one is to create unique and distinct ranges of rows to process, spawn multiple P/SQL processes, and provide each with a unique range of rows to process. In parallel.
So you need to look close at what you are trying to achieve, what the workloads are, and how to effectively decrease the workloads and increase the processing time of a workload.
For example - finding distinct column values. You can pay for that workload when wanting that distinct list. And each time afterward repeat that workload when wanting that distinct list. Or you can pay for that workload up-front with the DML that creates/updates those values - and use (for example) a materialised view to maintain a ready to use distinct list of values.
Same workload in essence - but paying once for it and up-front as oppose to each time you execute your code that needs to dynamically build that distinct list.
Kent Crotty did tests and showed stunning performance improvements with bulk collect and forall, up to 30x faster:Bulk processing is not a magical silver bullet. It is a tool. And when correctly use, the tool does exactly what it was designed to do.
The problem is using a hammer to drive in screws - instead of a screwdriver. There's nothing "stunning" about using a screwdriver. It is all about using the correct tool.
If the goal of the swap daemon is to free up "idle" chunks of memory, and try to use that memory for things like file cache instead, what does that have to do with bulk processing?The swap daemon reads virtual memory pages from swap space into memory, and writes virtual pages from memory to swap space.
What does it have to do with bulk processing? A bulk fetch reads data from the SGA (buffer cache) into the PGA (private process memory space). The larget the fetch, the more memory is required. If for example 50% of server memory is required for a bulk collection that is 2GB in size, then that will force in-use pages from memory to swap space.. only to be swapped back again as it is needed, thereby forcing other in-use pages to swap. The swap daemon will consume almost all the CPU time swapping hot pages continually in and out of memory.
Maybe you are looking for
-
Desktop pictures do NOT rotate/change on secondary display
For some peculiar reason, my desktop pictures do NOT change / rotate on my secondary display. I have a MacBook Pro 15" (Late 2007) running Snow Leopard 10.6.2 and I have dual displays. My primary display (the MBP screen) DOES change / rotate picture
-
Need access the E1000's web-based setup page.
I have a Linksys E1000 wireless router, and I seem to have either written down the password incorrectly or am using the wrong one. Regardless, I can not access the web-based setup for the router. Is there anyway to reset the username and password for
-
I'm trying to make a query that compares the hours, filled in by an employee in OTL (oracle time and labour) for a certain projectnumber, with the actually transferred hours to this projectnumber in oracle projects. The expenditure date on the otl si
-
No audio in a tv episode download
I have downloaded a tv episode and there is no audio track
-
Text resizes when cutting and pasting
Help? When I cut and paste text from one scene or area to another, the text changes sizes and does not look uniform to the next. How do I eliminate that or at least figure out how to make the text the same size (re: the original text may be 32, but t