Query help - distinct
Is there a more efficient way to write this query besides using DISTINCT?
I’m trying to count the number of unique account numbers by each INT.
My query works but it’s a little slow.
SELECT
act.INT
,COUNT(DISTINCT(plm.ACCT_NUMBER)) ACCT#
FROM…
GROUP BY act.INT
Any information would be greatly appreciated.
Thanks,
x
Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL.
And you need to read and download the PDF for:
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> Is there a more efficient way to write this query besides using DISTINCT? I’m trying to count the number of unique account numbers by each INT. My query works but it’s a little slow. <<
The INT is a reserved word (INTEGER) in SQL so it should never be a column name. Using special symbols like # in a data element name is another serious ISO violation and awful programming. Use only Latin letters, digits and the minimal set of punctuation marks
from the common Unicode subset. This will let yuou use the same data element names in all the ISO standard languages zand tooils.
If you have the right indexes, the COUNT(DISTINCT <expr>) should perform fine.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Similar Messages
-
Hi..
I have the following query..
I'm getting the following o/p...
Offshore In-house 1858 616
Offshore In-house 1858 615
Onshore In-house 1858 611
Offshore In-house 1858 923
Offshore In-house 1858 613
Onshore In-house 1858 941
Onshore In-house 1858 940
Onshore In-house 1858 890Can I get distinct onshores and offshores values..like in the above case only one in-house for offshore and one in-house for onshore and if there are multiple repeating values for offshore and on shrore..I need only dinstinct values in both offshore and onshore..
Any help..?
Edited by: user10280715 on Apr 14, 2009 10:21 AMIf I have a result set like this..
Offshore In-house 1858 616
Offshore In-house 1858 615
Onshore In-house 1858 611
Offshore In-house 1858 923
Offshore In-house 1858 613
Onshore In-house 1858 941
Onshore In-house 1858 940
Onshore In-house 1858 890the o/p I'm looking for..
Offshore In-house 1858 616
Onshore In-house 1858 890If I have different result set like..
Offshore In-house 1858 616
Offshore In-house 1858 615
Offshore aaaaaaaa 1859 611
Offshore aaaaaaaa 1859 923
Offshore In-house 1858 613
Onshore In-house 1858 941
Onshore In-house 1858 940
Onshore eeeeeee 1860 890
Onshore eeeeeee 1860 941I'm looking for..
Offshore In-house 1858 616
Offshore aaaaaaaa 1859 611
Onshore In-house 1858 941
Onshore eeeeeee 1860 890Is it possible.. -
Query Help:
http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
The above was my previous posting, which was not clear..so Iam restating my problem as follows....
I have the following tables
Customer(custID, Name, Address)
Order(custID, OrderID, orderDate)
CreditCard(custID, creditCard#, creditCardType)
Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
Order:
100,A001,11/22/03
100,A002,11/24/03
100,A003,12/02/03
CreditCard:
100,42323232..., VISA
100,5234234...., MASTER
Now how can I get
custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
data in minimum no. of records....
I think I have made my query clear..
now please help me guys...
thanks so much for your help.You are right.
But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
Can you please help me with the query
if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
With the following fields in my query result,
custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
from Customer, Order, CreditCard tables
Thanks so much for your htlp -
SQL Query Help - Is this possible or impossible????
Hi guys,
I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
For example,
I have 2 tables
The first table is:
1) COMPANY create table company (manufacturer varchar2(25),
date_established date,
location varchar2(25) );My sample test date is:
insert into company values ('Ford', 1902, 'USA');
insert into company values ('BMW', 1910, 'Germany');
insert into company values ('Tata', 1922, 'India');The second table is:
2) MODELS create table models (manufacturer varchar(25),
model varchar2(25),
price number(10),
year date,
current_production_status varchar2(1) ) ;My sample test data is:
insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
insert into models values ('Ford', 'Galaxy', 12000, 2008, 0);
insert into models values ('Ford', 'Escort', 10000, 1992, 1);
insert into models values ('BMW', '318', 17500, 2010, 0);
insert into models values ('BMW', '535d', 32000, 2006, 0);
insert into models values ('BMW', 'Z4', 10000, 1992, 0);
insert into models values ('Tata', 'Safari', 4000, 1999, 0);
insert into models values ('Tata', 'Sumo', 5500, 1996, 1);
insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
SELECT
com.manufacturer,
com.date_established,
com.location,
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
mod.current_production_status
FROM
company com,
models mod
WHERE
mod.manufacturer = com.manufacturer
and com.manufacturer IN ('Ford', 'BMW', 'Tata')
and mod.current_production_status IN (1,0)
ORDER BY
mod.current_production_status DESCWhat I want the query to output is this:
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
BMW 1910 Germany - - - 0
Tata 1922 India Sumo 5500 1998 1If current_production_status is 1 it means this particular model has been discontinued
If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
So the query should output the one row where current_production_status is 1 for each manufacturer.
If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
My query as it is above will output all the records where current status is 1 or 0 like this
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
Tata 1922 India Sumo 5500 1998 1
Ford 1902 USA - - - 0
Ford 1902 USA - - - 0
BMW 1910 Germany - - - 0
BMW 1910 Germany - - - 0
BMW 1910 Germany - - - 0
Tata 1922 India - - - 0
Tata 1922 India - - - 0However this is not what I want.
Any ideas how I can achieve the result I need?
Thanks!
P.S. Database version is '10.2.0.1.0'Hi Vishnu,
Karthiks query helped...
But this is the problem I am facing...
SELECT
com.manufacturer,
com.date_established,
com.location,
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
mod.current_production_status
FROM
company com,
models mod
WHERE
mod.manufacturer = com.manufacturer
and com.manufacturer = 'Ford'
and mod.current_production_status IN (1,0)
ORDER BY
mod.current_production_status DESCThe value of:
and com.manufacturer = 'Ford'will be dependent on front end user input....
When I run the query above I get all the rows where current_production_status is either 1 or 0.
I only require the rows where current_production_status is 1.
So if I amend it to look like this:
and mod.current_production_status = 1This works....
BUT if a user now passes in more than one manufacturer EG:
and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
So like this:
com.manufacturer com.date_established com.location mod.model mod.price mod.year mod.current_production_status
Ford 1902 USA Escort 10000 1992 1
BMW 1910 Germany - - - 0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
Thanks you so much!
This is really driving me insane :-( -
hii
i need a query help
i have two tables
the 1st table will look like this
associate id weekid no.of. hours
4000 810 40
4000 820 30
4000 830 60
4000 840 70
2nd table will look like this
associate id weekid no.of.hours
4000 810 40
4000 820 70
4000 830 130
4000 840 200
so when i subtract the last two records frm each other in the second table the value should be equal to the no.of.hours in the first table.. for example
the query shud consider the last record and one before the last record and the difference between two records shud be equal to the value in the 1st table
for example
consider week id 830 and 840
in second table 830=130
840=200
when u subtraced both values the difference shud be equal to value in the 1st table for tht week id
1 ---->>>> 840 - 830
=200 - 130
=70
in first table 840 has 70 hrs
like this it shud check with all records and it shud return only the records which are not equal
regards
srikanthThis..?
sql>select * from t1;
A_ID W_ID HRS
4000 810 40
4000 820 30
4000 830 60
4000 840 70
4000 850 80
sql>select * from t2;
A_ID W_ID HRS
4000 810 40
4000 820 70
4000 830 130
4000 840 200
4000 850 260
sql>
select a_id,w_id,hrs,sum_hrs
from(
select t1.a_id a_id,t1.w_id w_id,t1.hrs hrs,t2.hrs sum_hrs,
t2.hrs - nvl(lag(t2.hrs) over(order by t1.w_id),0) diff
from t1,t2
where t1.w_id = t2.w_id)
where diff != hrs;
A_ID W_ID HRS SUM_HRS
4000 850 80 260 -
Query Help (Left Join?)
Hi all
Im trying to write a query and am having problems with the way that the data is displayed.
My issue is essentially with one column EMPL_STAT_CD.
Within this column contains diffrent words standing for diffrent things such as Table, Lamp etc.
With my query i am specifically looking for everyone that has bought a Table or a table AND lamp.
How i want the data to be displayed is
table Blank
table Blank
Table Blank
Table Lamp
Table Blank
Table Lamp
Im pretty sure i can do a left outer join to display all the data in the left table, but am having problems with displaying the right table with the blanks.
Current Query
SELECT
DISTINCT(A.PRSN_INTN_ID),
B.FRST_NM AS FIRST_NAME,
B.MID_NM AS MIDDLE_NAME,
B.LAST_NM AS LASTNAME,
B.BRTH_DT AS BIRTH_DATE,
A.EMPL_CAT_ID AS EMPLOYMENT_ID,
A.EE_EMPLCAT_EFBEGDT AS BEGIN_DATE,
C.ADDR_LINE_1_TX AS ADDRESS,
C.CITY_NM AS CITY,
C.ST_CD AS PROVINCE,
C.ZIP_CD AS POSTAL_CODE,
C.CTRY_CD AS COUNTRY_CODE,
B.PRIM_LANG_CD AS LANGUAGE,
D.DLVR_GRSS_AT AS PENSION_AMOUNT,
FROM
PRSN B,
PRSN_ADDR C,
PRSN_TXDS_DLVR D,
PRSN_DBPMTINST E,
EE_EMPL_CAT A
WHERE A.PRSN_INTN_ID = B.PRSN_INTN_ID AND
A.PRSN_INTN_ID = C.PRSN_INTN_ID AND
A.PRSN_INTN_ID = D.PRSN_INTN_ID AND
A.PRSN_INTN_ID = E.PRSN_INTN_ID AND
D.PMT_ID = E.PMT_ID AND
D.PMT_EFDT = '2008-03-01'
AND E.DB_PMTINST_STAT_CD = 'A'
AND E.PMT_INST_EFENDDT = '2299-12-31'
AND E.PMT_ADJ_CD NOT IN ('R', 'A')
AND E.PMT_ID IN(1000,6000,2510,2520)
AND B.CURR_RSLT_CD = 'Y'
AND A.EMPL_CAT_ID IN(Table,Lamp)
AND A.EE_EMPLCAT_EFENDDT='2299-12-31'
AND C.ADDR_ID = 10
AND C.PRSN_ADDR_EFENDDT = '2299-12-31'
AND C.CURR_RSLT_CD = 'Y'
Any input greatly appreciatedYou don't have a query problem you have a design problem that goes back to database basics.
Never, ever, store multiple values in a single column.
Fix your design and the problem goes away.
http://www.psoug.org/reference/normalization.html -
Query help in select Distinct on one column.
CREATE GLOBAL TEMPORARY TABLE Table1 (
ID1 varchar2(100) ,
Name1 varchar2(100),
Name11 varchar2(100)
insert into Table1 values ('a','n1','h3');
insert into Table1 values('b','n2','h2');
insert into Table1 values('a','n3','h1');
insert into Table1 values('c','n4','h5');
insert into Table1 values ('c','n5','h4');
insert into Table1 values('d','n6','h6');
select * from Table1;
ID1,NAME1, NAME11
a, n1, h3
b, n2, h2
a, n3, h1
c, n4, h5
c, n5, h4
d, n6, h6
I am trying to select distinct ID1 and all values associated with it which is max row.I want to result as -
ID1,NAME1, NAME11
a, n3, h1
b, n2, h2
c, n5, h4
d, n6, h6
Can you please help me to write simple query to get above result.
Edited by: 871447 on Jul 25, 2011 9:42 AM
Edited by: 871447 on Jul 25, 2011 9:45 AMHi,
Do a self-join, to combine the two rows for each value of id1 onto one output row.
Make it an outer join, in case there is only one row with a vlaue for id1.
SELECT l.id1
, l.name1
, NVL ( r.name11
, l.name11
) AS name11
FROM table1 l
LEFT OUTER JOIN table1 r ON l.id1 = r.id1
AND l.name1 < r.name1
;Edited by: Frank Kulash on Jul 25, 2011 12:57 PM
Sorry, I mis-read the problem.
Lee's solution, above, assumes that name1 is unique, as it is in your sample data.
What output would you want if that's not the case?
If name1 is not unique, but the combination of (id1, name1) is unique, then you can modify Lee's solution like this:
SELECT *
FROM table1
WHERE (id1, name1) IN (
SELECT id1
, MAX (name1)
FROM table1
GROUP BY id1
;Or, if you can't make any assumptions about uniqueness, you might need something like this:
WITH got_r_num AS
SELECT id1, name1, name11
, ROW_NUMBER () OVER ( PARTITION BY id1
ORDER BY name1 DESC
, name11 DESC
) AS r_num
FROM table1
SELECT id1, name1, name11
FROM got_r_num
WHERE r_num = 1
; -
Help with a query.. distinct
Hi All,
i have this table and data:
CREATE TABLE TB_INV_KX
(FCH_FECHA_HORA timestamp,
ID_PRODUCTO VARCHAR2(10),
CTD_INV_FIN VARCHAR2(10)
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 15:39:56,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','502');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 15:12:43,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','854');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:25,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','856');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:25,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','463');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:25,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','200');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:12,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','847');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:12,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','445');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:31:12,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','209');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','847');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','856');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','445');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','463');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','191');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','200');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:30:47,000000000','DD/MM/RR HH24:MI:SS,FF'),'25','500');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','839');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','848');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','429');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','447');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','199');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','208');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 10:28:45,000000000','DD/MM/RR HH24:MI:SS,FF'),'25','509');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:52:34,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','80');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:52:34,000000000','DD/MM/RR HH24:MI:SS,FF'),'17','70');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:52:34,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:52:34,000000000','DD/MM/RR HH24:MI:SS,FF'),'19','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:35:55,000000000','DD/MM/RR HH24:MI:SS,FF'),'23','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:35:04,000000000','DD/MM/RR HH24:MI:SS,FF'),'23','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:25:25,000000000','DD/MM/RR HH24:MI:SS,FF'),'18','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('15/08/12 10:24:56,000000000','DD/MM/RR HH24:MI:SS,FF'),'19','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'2','667');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'3','98');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'3','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'3','789');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'4','150');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'4','455');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'4','567');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'4','789');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'5','87');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'5','333');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'5','879');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'6','100');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'7','567');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'7','789');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'8','987');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'9','77');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'9','333');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'18','6');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'18','546');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'19','34');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'20','546');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'20','567');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'21','34');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'21','150');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'21','200');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'22','150');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'22','546');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'23','78');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'29','67');
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('10/08/12 15:14:53,902000000','DD/MM/RR HH24:MI:SS,FF'),'29','78');when i do:
SELECT DISTINCT ID_PRODUCTO,CTD_INV_FIN,FCH_FECHA_HORA FROM TB_INV_KX WHERE CTD_INV_FIN >=0 ORDER BY FCH_FECHA_HORA DESC;--the example result is
16 502 16/08/12 15:39:56,000000000
16 854 16/08/12 15:12:43,000000000
18 200 16/08/12 10:31:25,000000000
17 463 16/08/12 10:31:25,000000000
16 856 16/08/12 10:31:25,000000000
18 209 16/08/12 10:31:12,000000000
17 445 16/08/12 10:31:12,000000000
16 847 16/08/12 10:31:12,000000000
18 191 16/08/12 10:30:47,000000000
18 200 16/08/12 10:30:47,000000000
17 445 16/08/12 10:30:47,000000000
17 463 16/08/12 10:30:47,000000000
25 500 16/08/12 10:30:47,000000000
16 847 16/08/12 10:30:47,000000000
the the expect is:
16 502 16/08/12 15:39:56,000000000
18 200 16/08/12 10:31:25,000000000
17 463 16/08/12 10:31:25,000000000
25 500 16/08/12 10:30:47,000000000Hi,
xDeviates wrote:
Hi All,
i have this table and data:
CREATE TABLE TB_INV_KX
(FCH_FECHA_HORA timestamp,
ID_PRODUCTO VARCHAR2(10),
CTD_INV_FIN VARCHAR2(10)
Insert into TB_INV_KX (FCH_FECHA_HORA,ID_PRODUCTO,CTD_INV_FIN) values (to_timestamp('16/08/12 15:39:56,000000000','DD/MM/RR HH24:MI:SS,FF'),'16','502');
Thanks for posting the CREATE TABLE and INSERT statements. Don't forget to post the explanation of why you want the results you post from that sample data. You already know the reasons, so it should be easy; nobody else knwos the reasons, so they have to guess (if they feel like guessing), and often guess wrong.
when i do:
SELECT DISTINCT ID_PRODUCTO,CTD_INV_FIN,FCH_FECHA_HORA FROM TB_INV_KX WHERE CTD_INV_FIN >=0 ORDER BY FCH_FECHA_HORA DESC;--the example result is
16 502 16/08/12 15:39:56,000000000
16 854 16/08/12 15:12:43,000000000
18 200 16/08/12 10:31:25,000000000
17 463 16/08/12 10:31:25,000000000
16 856 16/08/12 10:31:25,000000000
18 209 16/08/12 10:31:12,000000000
17 445 16/08/12 10:31:12,000000000
16 847 16/08/12 10:31:12,000000000
18 191 16/08/12 10:30:47,000000000
18 200 16/08/12 10:30:47,000000000
17 445 16/08/12 10:30:47,000000000
17 463 16/08/12 10:30:47,000000000
25 500 16/08/12 10:30:47,000000000
16 847 16/08/12 10:30:47,000000000Not when I run it: I get 60 rows of output, not just the 16 above.
the the expect is:
16 502 16/08/12 15:39:56,000000000
18 200 16/08/12 10:31:25,000000000
17 463 16/08/12 10:31:25,000000000
25 500 16/08/12 10:30:47,000000000Why just those 4 rows? Why don't you want, to give just a couple of examples:
ID_PRODUCT LAST_CTD_I FCH_FECHA_HORA
3 100 10-AUG-12 03.14.53.902000 PM
29 67 10-AUG-12 03.14.53.902000 PM? This is another reason why you need to post an explanation.
Maybe you're looking for something like this:
SELECT id_producto
, MIN (ctd_inv_fin) KEEP (DENSE_RANK LAST ORDER BY fch_fecha_hora)
AS last_ctd_inv_fin
, MAX (fch_fecha_hora) AS fch_fecha_hora
FROM tb_inv_kx
WHERE ctd_inv_fin >= 0
GROUP BY id_producto
ORDER BY id_producto
;You'll notice this is similar to what Solomon posted earlier, but it includes the WHERE clause from the query you posted. Solomon showed how to get the latest fch_fecha_hora for each producto_id. I used the analytic LAST fucntion to get the ctd_inv_fin that is related to the latest fch_fecha_hora for each id_producto. -
Query help on Goods Receipt Query with AP Invoice
Looking for a little help on a query. I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice). I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start. SBO 2005 SP01. Any help would be great appreciated. Thanks
SELECT distinct 'GR',
D0.DocStatus,
D0.DocNum ,
D0.DocDate,
D0.DocDueDate,
D0.DocTotal,
'AP',
I0.DocStatus,
I0.DocNum ,
I0.DocDate,
I0.DocDueDate,
I0.DocTotal,
I0.PaidToDate
FROM
((OPDN D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
full outer join
(OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
WHERE
(D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
OR (I1.BaseType=20 AND I1.BaseEntry IN
(SELECT Distinct DocEntry
FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))Hi Dalen ,
I believe it is because of the condition
(D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
OR (I1.BaseType=20 AND I1.BaseEntry IN
(SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
Try changing
D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
Lets see what would be the result . Lets have some fun with troubleshooting
See what would be the difference in the result .
Thank you
Bishal -
Query help: query to return column that represents multiple rows
I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
I need a query to find all names that occur in both of two separate locations.
For example,
bob usa
bob mexico
dot mexico
dot europe
hal usa
hal europe
sal usa
sal mexico
The query in question, if given the locations usa and mexico, would return bob and sal.
Thanks for any help or advice,
-=beekyHow about this?
SELECT NAME
FROM <LOCATIONS_TABLE>
WHERE LOCATION IN ('usa','mexico')
GROUP BY NAME
HAVING COUNT(DISTINCT LOCATION) >= 2Results:
SQL> WITH person_locations AS
2 (
3 SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
4 SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
5 SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
6 SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
7 SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
8 SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
9 SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
10 SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
11 )
12 SELECT NAME
13 FROM person_locations
14 WHERE LOCATION IN ('USA','Mexico')
15 GROUP BY NAME
16 HAVING COUNT(DISTINCT LOCATION) >= 2
17 /
NAM
bob
salHTH!
Edited by: Centinul on Oct 15, 2009 2:25 PM
Added sample results. -
hi guys
i have sample data as mentioned below... need to find the duplicate rows where cd=cd and dt1=dt1 and tm1 difference should be less than or equal to 4 hrs..
i can get the data with the query written below but my problem is that i am not allowed to use in-built sql server function... can you help me in writing the same without using in-built function...
CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
select * From #t
WITH MyCTE (rn,id, dt1, tm1, cd)
AS(
select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
,BASE.dt1
,BASE.tm1
,base.cd base_cd
,LEAD.dt1 LEAD_START_DATE
,LEAD.tm1 LEAD_START_TIME
,lead.cd lead_cd
--,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
FROM MyCTE BASE
LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
AND BASE.rn = LEAD.rn+1
) b
)cif this code will not work for you then not sure if there are any other options
Converted the CTE into an actual temp table.
CTE and barebones T-SQL code are included in the script below.
CREATE TABLE #t (id INT,dt1 datetime, tm1 datetime,cd varchar(10))
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:20:00.000','TC')
INSERT INTO #t VALUES (101,'2013-04-24','1900-01-01 12:30:00.000','TC')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 14:30:00.000','MN')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 09:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-11-27','1900-01-01 09:50:00.000','LM')
INSERT INTO #t VALUES (101,'2013-07-06','1900-01-01 15:07:00.000','XY')
INSERT INTO #t VALUES (101,'2013-08-02','1900-01-01 15:07:00.000','MN')
select * From #t
;WITH MyCTE (rn,id, dt1, tm1, cd)
AS(
select row_number() over (partition by id ORDER BY dt1, tm1) rn,* from #t
select case when ((dt1 = lead_start_Date) and (ct <='4.0') and (base_cd = lead_cd)) then 'Duplicate_Req' else '' end dt123,* from
select abs(convert(decimal(5,1),datediff(MI,lead_Start_time,tm1)/60.00)) ct, * from
SELECT base.rn b_rn,LEAd.rn l_rn,BASE.id
,BASE.dt1
,BASE.tm1
,base.cd base_cd
,LEAD.dt1 LEAD_START_DATE
,LEAD.tm1 LEAD_START_TIME
,lead.cd lead_cd
--,DATEADD(dd,-1,LEAD.dt1) EXPECTED_END_DATE
FROM MyCTE BASE
LEFT JOIN MyCTE LEAD ON BASE.id = LEAD.id
AND BASE.rn = LEAD.rn+1
) b
)c
select * into #copy From #t order by id, cd, dt1, tm1
alter table #copy add seqno int identity(1,1)
select distinct y.id,y.cd,y.dt1,y.tm1,y.seqno,case when z.cd is not null then 'Duplicate_Req' else '' end dt123
from #copy y
left outer join
(select a.id,a.cd,a.dt1,a.tm1
From #copy a
left outer join #copy b
on a.id = b.id
and a.cd = b.cd
and a.dt1 = b.dt1
where a.seqno > b.seqno
and abs(datediff(MINUTE,b.tm1,a.tm1)) <= 240) z
on y.id = z.id
and y.cd = z.cd
and y.dt1 = z.dt1
and y.tm1 = z.tm1
order by y.dt1,y.tm1
drop table #copy
drop table #t -
Due Date
Invoice amount
Receipt Number
Payment Date
Paid amount.
For all Receipt I tried to link Invoice. RCT2 ORCT and OITR and ITR1 table to get all invoices and receipt including reconciled one. but my query is not linking reconciled invoices
Please help me to fix this issue.Dear Poonam,
Have you check this query or not?
Give a try to this query....
Select * from (SELECT distinct T2.[CardCode],
T2.[CardName], T2.[DocNum] [Invoice#], T2.[DocDate],
T2.[DocDueDate], T2.[DocTotal], T0.[ReconDate] [Paid Date],
T0.[Total] [Paid Amount],
(Select distinct T5.DocNum from
ORCT T5 inner join ITR1 T6 on T5.DocEntry = T6.SrcObjAbs and
T6.SrcObjTyp = '24' where T6.ReconNum = T0.ReconNum) [Payment Num]
FROM [dbo].[OITR] T0 INNER JOIN ITR1 T1 ON T0.ReconNum = T1.ReconNum
inner join OINV T2 on T1.[SrcObjAbs] = T2.DocEntry
and T1.SrcObjTyp = 13) A
Where A.[Payment Num] is not null
Let me know the feedback....
Regards,
Bala -
Dear Experts,
In the below query, on account payment details are not coming in crystal report whereas it is coming in SQLwb! Any suggestions?
SELECT distinct
T0.DocNum as 'Outgoing Transaction No', t0.address,T0.series,
T0.CardName as 'Vendor Name',
T0.Address as 'Vendor Address',
T2.Checknum as 'Cheque No',
T2.DueDate as 'Cheque Date',
T2.bankcode as 'Bank Code',
T6.BankName AS 'Bank Name',
T2.AcctNum AS 'Bank Account No',
T0.Comments,
CASE
WHEN T1.InvType ='18' then 'A/P Invoice'
WHEN T1.InvType ='19' then 'A/P Credit Memo'
WHEN T1.InvType ='30' then 'Journal Entry'
WHEN T1.InvType ='-2' then 'Opening Balance'
END AS "Invoice Type",
T1.DocEntry as 'Document No',
CASE
WHEN T1.InvType ='18' then T3.nUMaTcARD
WHEN T1.InvType ='19' then T4.nUMaTcARD
END AS "Vendor Ref No",
CASE
WHEN T1.InvType ='18' then T3.TaxDate
WHEN T1.InvType ='19' then T4.TaxDate
WHEN T1.InvType ='30' then T5.RefDate
WHEN T1.InvType ='-2' then T5.RefDate
END AS "Document Posting Date",
CASE
WHEN T1.InvType ='18' then T3.max1099
WHEN T1.InvType ='19' then T4.max1099
WHEN T1.InvType ='30' then T1.SumApplied
WHEN T1.InvType ='-2' then T5.LocTotal
END AS "Transaction Amount",
T3.WTSum as 'TDS Amount',
CASE
WHEN T1.InvType ='18'and ((T3.max1099-3)>(T3.WTSumT1.DcntSumT1.SumApplied)) then (T3.max1099-(T3.WTSumT1.DcntSumT1.SumApplied))
END AS "A/P Credit Memo aganist this A/P Invoice",
CASE
WHEN T1.InvType ='18' then T3.Comments
WHEN T1.InvType ='19' then T4.Comments
WHEN T1.InvType ='30' then T5.memo
WHEN T1.InvType ='-2' then T5.memo
END AS "Transaction Remarks",
T1.SumApplied as 'Amount Paying for Transaction',
T2.Checksum as 'Cheque Sum',
T0.Comments as 'Outgoing Payments Remarks'
CASE WHEN T1.InvType='18' Then (Select DocDate from OPCH where DocEntry=T1.DocEntry) END 'Posting Date'
FROM
OVPM T0
LEFT OUTER JOIN VPM2 T1 ON T0.DocEntry = T1.DocNum
--I want to use it in CR...
--Please advice...
LEFT OUTER JOIN VPM1 T2 ON T0.DocEntry = T2.DocNum
LEFT OUTER JOIN OPCH T3 ON T1.DocEntry = T3.DocEntry
LEFT OUTER JOIN ORPC T4 ON T1.DocEntry = T4.DocEntry
LEFT OUTER JOIN OJDT T5 ON T0.TransId = T5.TransId
LEFT OUTER JOIN ODSC T6 ON T2.BankCode = T6.BankCode
WHERE T0.DocNum= '919' and T0.Series= '123'You are right.
But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
Can you please help me with the query
if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
With the following fields in my query result,
custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
from Customer, Order, CreditCard tables
Thanks so much for your htlp -
Hi,
I was wondering if I could have some help with the query I have below for this general data set, please? I need to do it in a single SQL statement. We're currently running Oracle 10g. The piece I'm struggling with is identifying that the person has all the items in a collection and to include the collection in the resulting collection of items.
persons_items
person item
Ted cup
Ted saucer
Ted plate
Ted fork
Alice book
Alice thimble
Alice knife
Alice cup
Joe cup
Joe saucer
Joe plate
Joe knife
Joe fork
Joe spoon
Jessica spatula
Jessica dish
collections
collection_name item
crockery cup
crockery saucer
crockery plate
cutlery knife
cutlery fork
cutlery spoon
Query:
What single items and collections does Ted have? fork, crockery
What single items and collections does Alice have? book, thimble, knife, cup
What single items and collections does Joe have? crockery, cutlery
What single items and collections does Jessica have? spatula, dish
Thanks in advance.
PatExpanding on Brendan's solution...
For 11g:
SQL> ed
Wrote file afiedt.buf
1 WITH person_items AS (
2 SELECT 'Ted' person, 'cup' item FROM DUAL UNION
3 SELECT 'Ted', 'saucer' FROM DUAL UNION
4 SELECT 'Ted', 'plate' FROM DUAL UNION
5 SELECT 'Ted', 'fork' FROM DUAL UNION
6 SELECT 'Alice', 'book' FROM DUAL UNION
7 SELECT 'Alice', 'thimble' FROM DUAL UNION
8 SELECT 'Alice', 'knife' FROM DUAL UNION
9 SELECT 'Alice', 'cup' FROM DUAL UNION
10 SELECT 'Joe', 'cup' FROM DUAL UNION
11 SELECT 'Joe', 'saucer' FROM DUAL UNION
12 SELECT 'Joe', 'plate' FROM DUAL UNION
13 SELECT 'Joe', 'knife' FROM DUAL UNION
14 SELECT 'Joe', 'fork' FROM DUAL UNION
15 SELECT 'Joe', 'spoon' FROM DUAL UNION
16 SELECT 'Jessica', 'spatula' FROM DUAL UNION
17 SELECT 'Jessica', 'dish' FROM DUAL
18 ), collections AS (
19 SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
20 SELECT 'crockery', 'saucer' FROM DUAL UNION
21 SELECT 'crockery', 'plate' FROM DUAL UNION
22 SELECT 'cutlery', 'knife' FROM DUAL UNION
23 SELECT 'cutlery', 'fork' FROM DUAL UNION
24 SELECT 'cutlery', 'spoon' FROM DUAL
25 ), person_item_colls AS (
26 SELECT pi.person, pi.item, co.collection_name,
27 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
28 FROM person_items pi
29 LEFT JOIN collections co
30 ON co.item = pi.item
31 )
32 select person, listagg(collection_name,',') within group (order by collection_name) as collections
33 from (
34 SELECT DISTINCT person, collection_name
35 FROM person_item_colls
36 WHERE collection_name IS NOT NULL
37 AND n_col > 1
38 UNION ALL
39 SELECT person, item
40 FROM person_item_colls
41 WHERE collection_name IS NULL
42 OR n_col = 1
43 )
44* group by person
SQL> /
PERSON COLLECTIONS
Alice book,cup,knife,thimble
Jessica dish,spatula
Joe crockery,cutlery
Ted crockery,forkFor 10g:
SQL> ed
Wrote file afiedt.buf
1 WITH person_items AS (
2 SELECT 'Ted' person, 'cup' item FROM DUAL UNION
3 SELECT 'Ted', 'saucer' FROM DUAL UNION
4 SELECT 'Ted', 'plate' FROM DUAL UNION
5 SELECT 'Ted', 'fork' FROM DUAL UNION
6 SELECT 'Alice', 'book' FROM DUAL UNION
7 SELECT 'Alice', 'thimble' FROM DUAL UNION
8 SELECT 'Alice', 'knife' FROM DUAL UNION
9 SELECT 'Alice', 'cup' FROM DUAL UNION
10 SELECT 'Joe', 'cup' FROM DUAL UNION
11 SELECT 'Joe', 'saucer' FROM DUAL UNION
12 SELECT 'Joe', 'plate' FROM DUAL UNION
13 SELECT 'Joe', 'knife' FROM DUAL UNION
14 SELECT 'Joe', 'fork' FROM DUAL UNION
15 SELECT 'Joe', 'spoon' FROM DUAL UNION
16 SELECT 'Jessica', 'spatula' FROM DUAL UNION
17 SELECT 'Jessica', 'dish' FROM DUAL
18 ), collections AS (
19 SELECT 'crockery' collection_name, 'cup' item FROM DUAL UNION
20 SELECT 'crockery', 'saucer' FROM DUAL UNION
21 SELECT 'crockery', 'plate' FROM DUAL UNION
22 SELECT 'cutlery', 'knife' FROM DUAL UNION
23 SELECT 'cutlery', 'fork' FROM DUAL UNION
24 SELECT 'cutlery', 'spoon' FROM DUAL
25 ), person_item_colls AS (
26 SELECT pi.person, pi.item, co.collection_name,
27 Count(*) OVER (PARTITION BY pi.person, co.collection_name) n_col
28 FROM person_items pi
29 LEFT JOIN collections co
30 ON co.item = pi.item
31 )
32 select person, ltrim(sys_connect_by_path(collection_name,','),',') as collections
33 from (
34 select person, collection_name, row_number() over (partition by person order by collection_name) as rn
35 from (
36 SELECT DISTINCT person, collection_name
37 FROM person_item_colls
38 WHERE collection_name IS NOT NULL
39 AND n_col > 1
40 UNION ALL
41 SELECT person, item
42 FROM person_item_colls
43 WHERE collection_name IS NULL
44 OR n_col = 1
45 )
46 )
47 where connect_by_isleaf = 1
48 connect by person = prior person and rn = prior rn + 1
49* start with rn = 1
SQL> /
PERSON COLLECTIONS
Alice book,cup,knife,thimble
Jessica dish,spatula
Joe crockery,cutlery
Ted crockery,fork -
SQL Query with Distinct and Count is wrong.
Hello,
i have another problem with a query.
Here the Data:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
CREATE TABLE TABLE_1
( "ORDER_NR" VARCHAR2 (12)
, "PRIORITY" VARCHAR2 (2)
, "WO_STATUS" VARCHAR2 (1)
, "STATUS_DATE" DATE
, "ART_NR" VARCHAR2 (9)
, "DESCRIPTION" VARCHAR2 (255)
, "PRICE" VARCHAR2 (10)
CREATE TABLE TABLE_2
( "ART_NR" VARCHAR(9)
, "MODELL" VARCHAR2(10)
, "MANUFACT" VARCHAR2(20)
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('05-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300612', '12', 'U', TO_DATE('06-FEB-13 10:22:39','DD-MON-RR HH24:MI:SS'), '005231987', '1ST ANNUAL SERVICE', '5000.2546');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '05', 'U', TO_DATE('05-FEB-13 11:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '5269.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('06-FEB-13 12:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '1ST BIENNIAL SERVICE', '1234.4468');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300638', '12', 'U', TO_DATE('07-FEB-13 13:38:39','DD-MON-RR HH24:MI:SS'), '005667821', '3RD ANNUAL SERVICE', '4366.7856');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300762', '12', 'U', TO_DATE('22-FEB-13 14:55:48','DD-MON-RR HH24:MI:SS'), '018743356', '3RD ANNUAL SERVICE', '4462.8632');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('22-FEB-13 08:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND ANNUAL SERVICE', '8762.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '05', 'U', TO_DATE('23-FEB-13 12:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '1ST BIENNIAL SERVICE', '3425.6643');
INSERT INTO TABLE_1 (ORDER_NR, PRIORITY, WO_STATUS, STATUS_DATE, ART_NR, DESCRIPTION, PRICE)
VALUES ('1KKA1Z300766', '12', 'U', TO_DATE('24-FEB-13 14:32:13','DD-MON-RR HH24:MI:SS'), '018743356', '2ND BIENNIAL SERVICE', '6678.6643');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005231987', 'X-RAY1', 'MANUFACT6');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('005667821', 'LASER', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT1');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT2');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT3');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT4');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT5');
INSERT INTO TABLE_2 (ART_NR, MODELL, MANUFACT)
VALUES ('018743356', 'VACCUM', 'MANUFACT6');
COMMIT;And my query:
SELECT T1.ART_NR
, T2.MODELL
, SUM(ROUND(T1.PRICE, 2)) AS TOTAL_PRICE
, COUNT(*) AS QTY
, TO_CHAR(T1.STATUS_DATE, 'MON-RR') AS MONTH
FROM TABLE_1 T1, TABLE_2 T2
WHERE T1.WO_STATUS = 'U'
AND T1.ART_NR = T2.ART_NR
AND TO_CHAR(T1.STATUS_DATE, 'MON-RR') = 'FEB-13'
GROUP BY T2.MODELL
, T1.ART_NR
, TO_CHAR(T1.STATUS_DATE, 'MON-RR')And the result:
ART_NR MODELL TOTAL_PRICE QTY MONTH
018743356 VACCUM 559916.16 96 FEB-13
005667821 LASER 173936.48 48 FEB-13
005231987 X-RAY1 120006 24 FEB-13My problem now is, the OTY field ist wrong it should count how often the equipment was in service in FEB-13 and group it by "MODELL" the MANUFACT field is not interesting for me, but this ist my problem, one Modell can have multible Manufacter and so i got a wrong count for my QTY.
The next step i need is to group the result also by Service type (annual or biennial), like this:
ART_NR MODELL TOTAL_PRICE QTY MONTH SERVICE_TYPE
018743356 VACCUM 1234.56 4 FEB-13 ANNUAL
018743356 VACCUM 4423.48 10 FEB-13 BIENNIAL
005667821 LASER 4783.11 2 FEB-13 ANNUAL
005667821 LASER 1123.77 22 FEB-13 BIENNIAL
005231987 X-RAY1 8966.12 6 FEB-13 ANNUAL
005231987 X-RAY1 7826.44 12 FEB-13 BIENNIALThis values are only out of my head, not the table, only to show what i need.
Thanks for your help.
Greets ReinhardHi,
Here's one way:
WITH got_groups AS
SELECT art_nr
, TRUNC (status_date, 'MONTH') AS month
, CASE
WHEN UPPER (description) LIKE '%ANNUAL%'
THEN 'ANNUAL'
WHEN UPPER (description) LIKE '%BIENNIAL%'
THEN 'BIENNIAL'
END AS service_type
, TO_NUMBER (price) AS price
FROM table_1
WHERE status_date >= DATE '2013-02-01'
AND status_date < DATE '2013-03-01'
, table_2_summary AS
SELECT DISTINCT art_nr, modell
FROM table_2
SELECT g.art_nr
, s.modell
, ROUND ( SUM (g.price)
, 2
) AS total_price
, COUNT (*) AS qty
, g.month
, service_type
FROM got_groups g
JOIN table_2_summary s ON s.art_nr = g.art_nr
GROUP BY g.art_nr
, s.modell
, g.month
, g.service_type
;The reason why your aggregates were originally too high is that you have a many-to-many relationship between the tables. The tables are related only by art_nr, but art_nr is not unique in either table. Look at art_nr '005231987', example. There ate 2 rows in table_1 with that art_nr, and 6 rows in table_2 with the same art_nr. If we join on art_nr, then both of the rows in table_1 will match each of the 6 rows in table_2, so the COUNT will be 2 * 6 = 12, and in the SUM, each of the numbers from table_1 will get added 6 times.
Why is table_2 designed the way it is? Cn there be multiple modells for the same art_nr? If so, what would you want for output? If there can only be 1 modell for each art_nr, then a better design would be to have a table that just had one row per art_nr, and included the modell column, and another table to show which manufacturers produce each art_nr. In this problem, you wouldn't need the manufacturers table, and the other table already has unique art_nrs, so you wouldn't need anything like the sub-query table_2_summary.
Don't store price in a VARCHAR2 column. Storing NUMBERs in a VARCHAR2 column is just asking for problems. Why not use a NUMBER column instead.
You'll notice that I used ROUND (SUM ... where you use SUM ( ROUND. The results might be a little different because of rounding errors. ROUND ( SUM only has to call ROUND once per group (5 times in this example) instead of once per row (16 times in this example). The less rounding you do, the less rounding error creeps in. Also, since there are fewer function calls, it's more convenient. (Of course, you'll never notice the difference between calling ROUND 5 times or 16 times, but in a real-life exampe, the difference could be between calling it 50 times or calling it 16000 times.) If you really need to use SUM (ROUND, you can.
Maybe you are looking for
-
Connecting Ibook to TV - Need Help
Hello. First of all let me thank all the kind people here on the forum. My computer died a few months ago, and the screen has basically died. Im looking to use my laptop through my tv. I have read the support sections of this site and am a tad confus
-
Hi There, I have MaxL to load data into the essbase: import database Finance.Finance data connect as "password" identified by "password" using server rules_file FinanceRule on error write to "d:\\log\\hDataLoad.err" ; It works without any issue. But
-
How to know where a GL account is used
hello all as FI is not my speciality, can someone explain to me how can I know where a GL account is being used? meaning, we link GL accounts to material groups via valuation class, is there a way to know which valuation class is linked to a specific
-
I am very new to swing, and have gone thru the swing tutorial looking for how to make the cursor invisible, and I just cant seem to find it. Can someone help me out? I have a textarea and I want no blinking cursor in the area. THANKS John McDonald
-
Adobe Flash not installing on OS X 10.8.5?
Hi everyone, I have been trying to update Flash Player on my Macbook Air, but for some reason every time I open the .dmg and click on the installer the program freezes and I get the wheel of death. I did the usual check and uninstalled Flash complete