SQL PL SQL - Group By
Hi All,
Thanks for your time in advance. I have situation where I need to group amounts by different field but one of the fields need to be re-organized. Not sure, how to better explain this in text. But, please see below example. Using 11g
SELECT 80 AMOUNT, 111 ACCOUNT_NUM, 123 CHECK_NUM FROM DUAL
UNION ALL
SELECT 100 AMOUNT, 111 ACCOUNT_NUM, 124 CHECK_NUM FROM DUAL
UNION ALL
SELECT 120 AMOUNT, 111 ACCOUNT_NUM, 125 CHECK_NUM FROM DUALDesired Result:
AMOUNT ACCOUNT_NUM CHECK_NUM
200 111 123,124,125Thanks
788729 wrote:
Using 11g11g is not clear enough. If it is 11.2, use LISTAGG:
WITH T AS (
SELECT 80 AMOUNT, 111 ACCOUNT_NUM, 123 CHECK_NUM FROM DUAL UNION ALL
SELECT 100 AMOUNT, 111 ACCOUNT_NUM, 124 CHECK_NUM FROM DUAL UNION ALL
SELECT 120 AMOUNT, 111 ACCOUNT_NUM, 125 CHECK_NUM FROM DUAL
SELECT SUM(AMOUNT) AMOUNT,
ACCOUNT_NUM,
LISTAGG(CHECK_NUM,',') WITHIN GROUP(ORDER BY CHECK_NUM) CHECK_NUM
FROM T
GROUP BY ACCOUNT_NUM
AMOUNT ACCOUNT_NUM CHECK_NUM
300 111 123,124,125
SQL> SY.
Similar Messages
-
Please help: WebLogic + BI + SQL Group Authenticator
Hi all, i have big problem with solution on my company project. I please somebody help me.
This is my problem:
I have bifoundation_domain :
WebLogic Server Version: 10.3.5.0
EM 11g
Oracle Business Intelligence 11.1.1.7.0
with this structure:
bifoundation_domain
|- AdminServer
|- bi_cluster
|- bi_server1
So and i need use Weblogic embedded LDAP (DefaultAuthenticator in realms security providers) and i need loading GROUPS from DATABASE. I read and tried a lot of articles, blogs, manuals but
within positive result.
My procedure is:
In WLS console :
- create jdbc datasource with name "bip_apps_DS"
- create BI SQL Group provider (with name BIGroupLoader) with this settings
<sec:authentication-provider xmlns:ext="http://xmlns.oracle.com/weblogic/security/extension" xsi:type="ext:bisql-group-providerType">
<sec:name>BIGroupLoader</sec:name>
<sec:control-flag>OPTIONAL</sec:control-flag>
<ext:data-source-jndi-name>bip_apps_DS</ext:data-source-jndi-name>
<ext:sql-list-member-groups>SELECT ROLE_NAME FROM V_SYS_AUTH_ROLES WHERE LOGIN_NAME = ?</ext:sql-list-member-groups>
<ext:sql-list-groups>SELECT NAME FROM UA_ROLES WHERE NAME LIKE ?</ext:sql-list-groups>
<ext:sql-group-exists>SELECT NAME FROM UA_ROLES WHERE NAME = ?</ext:sql-group-exists>
<ext:sql-is-member>SELECT LOGIN_NAME FROM V_SYS_AUTH_ROLES WHERE ROLE_NAME = ? AND LOGIN_NAME = ?</ext:sql-is-member>
<ext:sql-get-group-description>SELECT DESCRIPTION FROM UA_ROLES WHERE NAME = ?</ext:sql-get-group-description>
</sec:authentication-provider>
(my DB schema is correct)
and i move him on first place in providers list.
So after these steps in WLS console i see in security realm->groups my groups from DB. Everything is OK.
Now i need use GROUPS from my database in EM in the context of create BI users roles (maping BI application roles on GROUPS (enterprise roles)).
So i created a database adapter for the Virtualized Identity Store
this is it:
<?xml version = '1.0' encoding = 'UTF-8'?>
<adapters schvers="303" version="1" xmlns="http://www.octetstring.com/schemas/Adapters" xmlns:adapters="http://www.w3.org/2001/XMLSchema-instance">
<dataBase id="directoryType" version="0">
<root>%ROOT%</root>
<active>true</active>
<serverType>directoryType</serverType>
<routing>
<critical>true</critical>
<priority>50</priority>
<inclusionFilter/>
<exclusionFilter/>
<plugin/>
<retrieve/>
<store/>
<visible>Yes</visible>
<levels>-1</levels>
<bind>true</bind>
<bind-adapters/>
<views/>
<dnpattern/>
</routing>
<pluginChains xmlns="http://xmlns.oracle.com/iam/management/ovd/config/plugins">
<plugins>
<plugin>
<name>VirtualAttribute</name>
<class>oracle.ods.virtualization.engine.chain.plugins.virtualattr.VirtualAttributePlugin</class>
<initParams>
<param name="ReplaceAttribute" value="uniqueMember={cn=%uniquemember%,ou=people,ou=myrealm,dc=bifoundation_domain}"/>
</initParams>
</plugin>
</plugins>
<default>
<plugin name="VirtualAttribute"/>
</default>
<add/>
<bind/>
<delete/>
<get/>
<modify/>
<rename/>
</pluginChains>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>%URL%</url>
<user>%USER%</user>
<password>%PASSWORD%</password>
<ignoreObjectClassOnModify>false</ignoreObjectClassOnModify>
<includeInheritedObjectClasses>true</includeInheritedObjectClasses>
<maxConnections>10</maxConnections>
<mapping>
<joins/>
<objectClass name="groupofuniquenames" rdn="cn">
<attribute ldap="cn" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
<attribute ldap="description" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
<attribute ldap="uniquemember" table="V_SYS_AUTH_ROLES" field="LOGIN_NAME" type=""/>
</objectClass>
</mapping>
<useCaseInsensitiveSearch>true</useCaseInsensitiveSearch>
<connectionWaitTimeout>10</connectionWaitTimeout>
<oracleNetConnectTimeout>0</oracleNetConnectTimeout>
<validateConnection>false</validateConnection>
</dataBase>
</adapters>
and run command to register:
./libovdadapterconfig.sh -adapterName BIGroupLoader -adapterTemplate bi_sql_groups_adapter_template.xml
-host localhost -port 7001 -userName weblogic -domainPath /OFM/BI/user_projects/domains/bifoundation_domain
-dataStore DB -root ou=people,ou=myrealm,dc=bifoundation_domain -contextName default -dataSourceJNDIName bip_apps_DS
Adapter is creatted successfully within errors!
I restarted managed server(bi_server1) and AdminServer, all bi commponets etc. BUT WITHOUT RESULT. I still dont see GROUPS in Enterprise manager in
BI->coreapplication->security->application roles
I tried set in security setting of webLogic domain in EM virtualize=true.
This procedure is described on all sites but not funkcionaly for me. Do you know somebody where is mistake? Etc. need i installing OVD server? I dont know. Please helm me. after 10 days i really hopeless :( ..so sorry for my englishIf you are still looking for sol? send me email [email protected]
-
Please help: WebLogic + BI + Bi SQl Group Loader
Hi all, i have big problem with solution on my company project. I please somebody help me.
This is my problem:
I have bifoundation_domain :
WebLogic Server Version: 10.3.5.0
EM 11g
Oracle Business Intelligence 11.1.1.7.0
with this structure:
bifoundation_domain
|- AdminServer
|- bi_cluster
|- bi_server1
So and i need use Weblogic embedded LDAP (DefaultAuthenticator in realms security providers) and i need loading GROUPS from DATABASE. I read and tried a lot of articles, blogs, manuals but
within positive result.
My procedure is:
In WLS console :
- create jdbc datasource with name "bip_apps_DS"
- create BI SQL Group provider (with name BIGroupLoader) with this settings
<sec:authentication-provider xmlns:ext="http://xmlns.oracle.com/weblogic/security/extension" xsi:type="ext:bisql-group-providerType">
<sec:name>BIGroupLoader</sec:name>
<sec:control-flag>OPTIONAL</sec:control-flag>
<ext:data-source-jndi-name>bip_apps_DS</ext:data-source-jndi-name>
<ext:sql-list-member-groups>SELECT ROLE_NAME FROM V_SYS_AUTH_ROLES WHERE LOGIN_NAME = ?</ext:sql-list-member-groups>
<ext:sql-list-groups>SELECT NAME FROM UA_ROLES WHERE NAME LIKE ?</ext:sql-list-groups>
<ext:sql-group-exists>SELECT NAME FROM UA_ROLES WHERE NAME = ?</ext:sql-group-exists>
<ext:sql-is-member>SELECT LOGIN_NAME FROM V_SYS_AUTH_ROLES WHERE ROLE_NAME = ? AND LOGIN_NAME = ?</ext:sql-is-member>
<ext:sql-get-group-description>SELECT DESCRIPTION FROM UA_ROLES WHERE NAME = ?</ext:sql-get-group-description>
</sec:authentication-provider>
(my DB schema is correct)
and i move him on first place in providers list.
So after these steps in WLS console i see in security realm->groups my groups from DB. Everything is OK.
Now i need use GROUPS from my database in EM in the context of create BI users roles (maping BI application roles on GROUPS (enterprise roles)).
So i created a database adapter for the Virtualized Identity Store
this is it:
<?xml version = '1.0' encoding = 'UTF-8'?>
<adapters schvers="303" version="1" xmlns="http://www.octetstring.com/schemas/Adapters" xmlns:adapters="http://www.w3.org/2001/XMLSchema-instance">
<dataBase id="directoryType" version="0">
<root>%ROOT%</root>
<active>true</active>
<serverType>directoryType</serverType>
<routing>
<critical>true</critical>
<priority>50</priority>
<inclusionFilter/>
<exclusionFilter/>
<plugin/>
<retrieve/>
<store/>
<visible>Yes</visible>
<levels>-1</levels>
<bind>true</bind>
<bind-adapters/>
<views/>
<dnpattern/>
</routing>
<pluginChains xmlns="http://xmlns.oracle.com/iam/management/ovd/config/plugins">
<plugins>
<plugin>
<name>VirtualAttribute</name>
<class>oracle.ods.virtualization.engine.chain.plugins.virtualattr.VirtualAttributePlugin</class>
<initParams>
<param name="ReplaceAttribute" value="uniqueMember={cn=%uniquemember%,ou=people,ou=myrealm,dc=bifoundation_domain}"/>
</initParams>
</plugin>
</plugins>
<default>
<plugin name="VirtualAttribute"/>
</default>
<add/>
<bind/>
<delete/>
<get/>
<modify/>
<rename/>
</pluginChains>
<driver>oracle.jdbc.driver.OracleDriver</driver>
<url>%URL%</url>
<user>%USER%</user>
<password>%PASSWORD%</password>
<ignoreObjectClassOnModify>false</ignoreObjectClassOnModify>
<includeInheritedObjectClasses>true</includeInheritedObjectClasses>
<maxConnections>10</maxConnections>
<mapping>
<joins/>
<objectClass name="groupofuniquenames" rdn="cn">
<attribute ldap="cn" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
<attribute ldap="description" table="V_SYS_AUTH_ROLES" field="ROLE_NAME" type=""/>
<attribute ldap="uniquemember" table="V_SYS_AUTH_ROLES" field="LOGIN_NAME" type=""/>
</objectClass>
</mapping>
<useCaseInsensitiveSearch>true</useCaseInsensitiveSearch>
<connectionWaitTimeout>10</connectionWaitTimeout>
<oracleNetConnectTimeout>0</oracleNetConnectTimeout>
<validateConnection>false</validateConnection>
</dataBase>
</adapters>
and run command to register:
./libovdadapterconfig.sh -adapterName BIGroupLoader -adapterTemplate bi_sql_groups_adapter_template.xml
-host localhost -port 7001 -userName weblogic -domainPath /OFM/BI/user_projects/domains/bifoundation_domain
-dataStore DB -root ou=people,ou=myrealm,dc=bifoundation_domain -contextName default -dataSourceJNDIName bip_apps_DS
Adapter is creatted successfully within errors!
I restarted managed server(bi_server1) and AdminServer, all bi commponets etc. BUT WITHOUT RESULT. I still dont see GROUPS in Enterprise manager in
BI->coreapplication->security->application roles
I tried set in security setting of webLogic domain in EM virtualize=true.
This procedure is described on all sites but not funkcionaly for me. Do you know somebody where is mistake? Etc. need i installing OVD server? I dont know. Please helm me.Hi,
You will not be able to see groups that you have defined in database in EM. To assign a database group to a role in EM go to BI->coreapplication->security->application roles & search for groups locate Advance Option at the bottom and check the box "Check to enter principal name here instead of searching from above. This option can be used for advanced scenarios related to custom authenticators". Now select Groups under Type and enter the name (exactly same) of the database group manually. Now you should be able to assign database groups to users authenticated through weblogic embedded LDAP.
Thanks -
Hi all,
I Hope anybody can help to provide the select statement that i need in my sitiuation.
I have one table name EVENTS. I want to make a select statement that can be produced the min(TIME) and max(TIME) time for one USERID.
This is my sql.
Select MIN (events.TIME1),
MAX (events.TIME1),
USERID
FROM events
Where date1=to_date('01/09/2006' , 'dd/mm/yyyy'')
Group by userid
This is the example value for TIME1 = '5/9/2005 10:38:57 AM'
This is the invalid sql, I dont know how to modify it, I dont want to group the address and reader. I only want to output the value. Can Anybody help me???
Select MIN (events.TIME1),address,reader
MAX (events.TIME1),
USERID
FROM events
Where date1=to_date('01/09/2006' , 'dd/mm/yyyy'')
Group by userid
CREATE TABLE EVENTS
ID NUMBER(10),
DATE1 DATE,
TIME1 DATE,
ADDRESS VARCHAR2(15 BYTE),
USERID VARCHAR2(50 BYTE),
READER VARCHAR2(20 BYTE)
)There may be more efficient ways to do it, but this works:
SQL> SELECT * FROM t;
ID DATE1 TIME1 ADDRE USERID READER
6 08-sep-2006 00:00:00 08-sep-2006 13:10:57 0001 N0001 1
5 07-sep-2006 00:00:00 07-sep-2006 13:10:57 0001 N0002 1
4 07-sep-2006 00:00:00 07-sep-2006 23:10:57 0005 N0001 2
3 07-sep-2006 00:00:00 07-sep-2006 22:30:57 0003 N0001 1
2 07-sep-2006 00:00:00 07-sep-2006 10:30:57 0002 N0001 2
1 07-sep-2006 00:00:00 07-sep-2006 10:38:57 0001 N0001 1
SQL> SELECT m.userid, minaddress, minreader, mintime,
2 maxaddress, maxreader, maxtime
3 FROM (SELECT date1, userid, minaddress, minreader, mintime
4 FROM (SELECT date1, userid, address minaddress, reader minreader,
5 time1 mintime,
6 ROW_NUMBER() OVER (PARTITION BY userid, date1
7 ORDER BY time1) rn
8 FROM t)
9 WHERE rn = 1) m,
10 (SELECT date1, userid, maxaddress, maxreader, maxtime
11 FROM (SELECT date1, userid, address maxaddress, reader maxreader,
12 time1 maxtime,
13 ROW_NUMBER() OVER (PARTITION BY userid, date1
14 ORDER BY time1 DESC) rn
15 FROM t)
16 WHERE rn = 1) x
17 WHERE m.userid = x.userid and
18 m.date1 = x.date1 and
19 m.userid = 'N0001' and
20 m.date1 = TO_DATE('07-sep-2006', 'dd-mon-yyyy');
USERID MINAD MINREADER MINTIME MAXAD MAXREADER MAXTIME
N0001 0002 2 07-sep-2006 10:30:57 0005 2 07-sep-2006 23:10:57John -
PL/SQL equivalent of T-SQL - "group function is not allowed here"
Hi all, hope someone can give me a hand as I'm pretty stuck! I have been trying to convert some MS SQL Server T-SQL statements into Oracle PL/SQL and am stuck on the below one:
SELECT
CA.AssessmentID,
(SELECT ProductName + ISNULL(' - ' + PrincipalBenefit,'')
FROM rptPolicySnapshot WHERE PolicyID = MAX(CA.PolicyID)
AND SnapshotID = 1),
MAX(CA.PolicyID)
FROM rptClaimInvoiceLineSnapshot CIL
INNER JOIN rptClaimAssessmentSnapshot CA
ON CIL.AssessmentID = CA.AssessmentID
AND CIL.SnapshotID = CA.SnapshotID
WHERE CIL.SnapshotID = 1
GROUP BY CA.AssessmentID
This works fine in MSSQL but returns the below error in Oracle:
'ORA-00934: group function is not allowed here'
If I take out the subquery the query works fine.
Any ideas as to the syntax? I am new to Oracle so not sure as to how I should go about writing this.
Thanks in advance!
LeoWITH x AS (SELECT ca.assessmentid,
MAX (ca.policyid) policy_id
FROM rptclaiminvoicelinesnapshot cil
INNER JOIN rptclaimassessmentsnapshot ca
ON cil.assessmentid = ca.assessmentid
AND cil.snapshotid = ca.snapshotid
WHERE cil.snapshotid = 1
GROUP BY ca.assessmentid
SELECT x.assessment_id,
x.policy_id,
productname + decode(principalbenefit,null,null,' - ' || principalbenefit ) prodname
FROM rptpolicysnapshot, x
WHERE policyid = x.policy_id
AND snapshotid = 1I think that's in the neighbourhood. -
-- SQL -- GROUP BY clause: non-aggregate fields mandate
Hello,
I was studying Databases, (particularly the retrieval of the data), and found something interesting.
While using an Aggregate Function in the SELECT clause, it is mandatory to have all the non-aggregate fields in the SELECT clause to be there in the GROUP BY clause.
For example,
SELECT dept_no, SUM(salary)
FROM employee
GROUP BY dept_no;
The above SQL works fine.
But, what if the user misses the dept_no in the GROUP BY clause or he/she misses the GROUP BY clause itself?
Certainly, it is an error.
Why is this error not handled by the database. I mean, the database should be smart/intelligent enough to add the GROUP BY clause by itself. So suppose, if I miss out the GROUP BY clause or miss a non-aggregate field from the SELECT clause when I am having at least one aggregate function on a field with at least one non-aggregated field in the SELECT clause, the database should check the GROUP BY clause at time of compilation and add the mandate missed out fields in the GROUP BY clause.
Example,
SQL1:_
SELECT dept_no, SUM(salary)
FROM employee
GROUP BY dept_no;
SQL2:_
SELECT dept_no, SUM(salary)
FROM employee;
Here, the SQL1 and SQL2, both should give me same outputs without an error.
I am unable to understand why is this not handled?Hi,
998478 wrote:
... If we mix aggregate and non-aggregate values then there must be a GROUP BY clause containing all the non-aggregate values. Why is this not handled by the database/compiler itself? It IS handled by the compiler itself. The compiler handles it by raising an error. The compiler has no way of knowing whether you want to remove something from the SELECT clause, or to add something to the GROUP BY clause, or not to use aggregate functions, or to use more aggregate functions, or some combination of the above. If the compiler re-wrote your code, and did any of these things automatically, it would be wrong more often than it was right, and you would (rightly) be complaining about its behavior.
For example, this is clearly wrong:
SELECT deptno
, job
, SUM (sal)
FROM scott.emp
GROUP BY deptno
;What is the right way to fix it?
<h3>1. Remove something from the SELECT clause</h3>
SELECT deptno
, SUM (sal)
FROM scott.emp
GROUP BY deptno
;<h3>2. Add something to the GROUP BY clause</h3>
SELECT deptno
, job
, SUM (sal)
FROM scott.emp
GROUP BY deptno
, job
;<h3>3. Not use aggregate functions</h3>
SELECT deptno
, job
, sal
FROM scott.emp
;<h3>4. Use more aggregate functions</h3>
SELECT deptno
, MIN (job)
, SUM (sal)
FROM scott.emp
GROUP BY deptno
;These aren't all the options, either. For example, the correct fix might be to use analytic functions instead of aggregate functions.
How can anybody say which of these is right? All of them are the right answer for some problem.
By the way, saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit over-simplified.
More completely, here are the ABC's of GROUP BY:
When you use a GROUP BY clause and/or an aggregate function, then everything in the SELECT clause must be:
(A) an <b>A</b>ggregate function,
(B) one of the "group <b>B</b>y" expressions,
(C) a <b>C</b>onstant, or
(D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can SELECT "TO_CHAR (TRUNC(dt), 'Mon-DD')").
Edited by: Frank Kulash on Apr 13, 2013 1:44 PM
Added code examples. -
PL SQL Grouping and Edit the Oldest Row in a Group
Event Table
CREATE TABLE "EVENT" ("EVENT_ID" VARCHAR2(36), "EVENTTYPE" VARCHAR2(110), "WHEN_OCCURRED" TIMESTAMP (6),"DESCRIPTION" VARCHAR2(255), "CURRENCY" VARCHAR2(3), "AMOUNT" NUMBER(38,8), "TRANSACTION_ID" VARCHAR2(255) )
Insert into EVENT (EVENT_ID,EVENTTYPE,DESCRIPTION,CURRENCY,AMOUNT,TRANSACTION_ID) values ('1','paymentEvent',to_timestamp('15-AUG-11 10.11.30.165000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'Payment Transaction Confirmed','USD',10','3');
Insert into EVENT (EVENT_ID,EVENTTYPE,DESCRIPTION,CURRENCY,AMOUNT,TRANSACTION_ID) values ('2','paymentEvent',to_timestamp('15-AUG-11 12.31.23.162000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Payment Transaction Confirmed','USD',10,'3085c51d-6425-4974-b2fb-f5bdc4d08137');
Transaction table
CREATE TABLE "TRANSACTION" ("TRANSACTION_ID" VARCHAR2(36 BYTE), "LAST_UPDATED" TIMESTAMP (6), "DESCRIPTION" VARCHAR2(255 BYTE), "TYPE" VARCHAR2(255 BYTE), "DEBIT_CREDIT" NUMBER(38,8), "ORIGINAL_ID" VARCHAR2(36 BYTE), "TYPE" VARCHAR2(255 BYTE))
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('c8ef1e7c-4134-45d8-9568-5da2fc41e137',to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed','SETTLEMENT',1,'3','1', 'debit');
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('8243cc1d-614d-4cfd-9c3b-b5cd44b3a67f',to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed','SETTLEMENT',1,'3','1', 'credit');
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('3',to_timestamp('15-AUG-11 10.11.30.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'testCharge','PAYMENT',10,null,null,null);
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('609f264b-1cef-4615-8f28-d8dae391dbba',to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed','SETTLEMENT',4,'3','1', 'debit');
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('3085c51d-6425-4974-b2fb-f5bdc4d08137',to_timestamp('15-AUG-11 12.31.23.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'testCharge','PAYMENT',10,null,null,null);
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('bafc4f83-d3b7-45f2-b35d-ba4101eebf3c',to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),Settle: Payment Transaction Confirmed','SETTLEMENT',2,'3085c51d-6425-4974-b2fb-f5bdc4d08137','2','debit');
Insert into TRANSACTION (TRANSACTION_ID,LAST_UPDATED,DESCRIPTION,TYPE,DEBIT_CREDIT,ORIGINAL_ID,EVENT_ID) values ('bbb6123b-8b70-45f2-b593-5b6bb2afd6b2',to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed','SETTLEMENT',2,'3','1','credit');
Result
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,TRX_DESC,GROSS,NET) values ('609f264b-1cef-4615-8f28-d8dae391dbba',to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),0,4,'3','Payment Transaction Confirmed',10,6);
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,TRX_DESC,GROSS,NET) values ('bbb6123b-8b70-45f2-b593-5b6bb2afd6b2',to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),2,0,'3','Correction: Payment Transaction Confirmed',0,2);
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,TRX_DESC,GROSS,NET) values ('c8ef1e7c-4134-45d8-9568-5da2fc41e137',to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,1,'3','Correction: Payment Transaction Confirmed'0,-1);
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,TRX_DESC,GROSS,NET) values ('8243cc1d-614d-4cfd-9c3b-b5cd44b3a67f',to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),1,0,'3','Correction: Payment Transaction Confirmed'0,1);
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,TRX_DESC,GROSS,NET) values ('bafc4f83-d3b7-45f2-b35d-ba4101eebf3c',to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,2,'3085c51d-6425-4974-b2fb-f5bdc4d08137','Payment Transaction Confirmed'10,8);
Explanation
* Each event table insert has a respective type='payment' insert in transaction table.
* My result interesting only about transaction type='settlement'
* One type = 'payment' transaction could have one type = 'settlement' by default. But in a some cases (an error) there be many type = settlement
* When we take transaction_id = '3' it has 4 'settlement' transactions
To the result these four(4) settlement takes and out of a four the oldest transaction should have a different presentation
(See result number 01)
If payment transaction has only one settlement transaction then the result description = Payment Transaction Confirmed
gross = respective event table amount
net = gross + credit - debit
if payment transaction has more than one settlement transaction then * Oldest transaction ( order by LAST_UPDATED)
description = Payment Transaction Confirmed
gross = respective event table amount
net = gross + credit - debit
* All other transactions
description = Correction: Payment Transaction Confirmed
gross = 0
net = if type = debit then net = -(debit) else credit
Appreciate your help for write a PL/SQL query that satisfies above.
I am thinking to
Group all relative settlement transactions into one unit.
Find oldest among them
Apply different logic for oldest
Apply common logic for othersStill need some help from you guys to convert my thoughts into SQL
ThanksYes. that is what I initially trying to do. But no success.
Please refer below my effort
Transaction table
CREATE TABLE "TRANSACTION" ("TRANSACTION_ID" VARCHAR2(36 BYTE), "OBJECT_TYPE" VARCHAR2(255 BYTE), "VERSION" NUMBER(19,0), "CREATED" TIMESTAMP (6), "LAST_UPDATED" TIMESTAMP (6), "DESCRIPTION" VARCHAR2(255 BYTE), "EXTERNAL_ID" VARCHAR2(255 BYTE), "TYPE" VARCHAR2(255 BYTE), "STATE" VARCHAR2(255 BYTE), "LAST_STATE_CHANGE" TIMESTAMP (6), "CHANNEL" VARCHAR2(255 BYTE), "MANDATE_ID" VARCHAR2(255 BYTE), "SUBSCRIPTION_ID" VARCHAR2(255 BYTE), "BULK_REFUND_TASK_ID" VARCHAR2(255 BYTE), "GROSS_CURRENCY" VARCHAR2(3 BYTE), "GROSS_AMOUNT" NUMBER(38,8), "TAX_CURRENCY" VARCHAR2(3 BYTE), "TAX_AMOUNT" NUMBER(38,8), "PAYER_ID" VARCHAR2(36 BYTE), "PAYEE_ID" VARCHAR2(36 BYTE), "ON_BEHALF_OF_PAYEE" VARCHAR2(255 BYTE), "ORIGINAL_ID" VARCHAR2(36 BYTE), "TRANSFER_ID" VARCHAR2(36 BYTE), "EVENT_ID" VARCHAR2(36 BYTE), "TERM_ID" VARCHAR2(36 BYTE), "CHARGE" NUMBER(1,0) DEFAULT 0, "TAGS_AND_VALUES" VARCHAR2(4000 BYTE), "LARGE_TAGS_AND_VALUES" CLOB, "EXPORT_PENDING" VARCHAR2(4 BYTE) DEFAULT 'TRUE')
Data
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('c8ef1e7c-4134-45d8-9568-5da2fc41e137','com.valista.trxe.model.Transaction',1,to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed',null,'SETTLEMENT','CONFIRMED',to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',1,'USD',0,'9f285bf7-46a1-4621-b165-dc782bf1d1ae','1c887a16-4344-4a80-8a11-f26d80824e4a',null,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14','f24be53d-7b78-455c-b1ac-f9fc242ec5ff','a2f09cbb-1555-4c8d-b401-0233982cfa7e','c6b70c01-7f9a-4d96-93a6-e8e1b568cf59',1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('8243cc1d-614d-4cfd-9c3b-b5cd44b3a67f','com.valista.trxe.model.Transaction',1,to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed',null,'SETTLEMENT','CONFIRMED',to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',1,'USD',0,'1c887a16-4344-4a80-8a11-f26d80824e4a','9f285bf7-46a1-4621-b165-dc782bf1d1ae',null,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14','ac5ae000-7ca8-4542-bf83-8d99e085e706','a2f09cbb-1555-4c8d-b401-0233982cfa7e','b70382c8-a05e-49c4-9919-ad765c5c5046',1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('61db88ec-ade8-4cc3-90f3-e49fa26dcf14','com.valista.trxe.model.Transaction',5,to_timestamp('15-AUG-11 10.11.30.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'testCharge',null,'PAYMENT','CONFIRMED',to_timestamp('15-AUG-11 10.11.30.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',10,'USD',0,'e8a58763-9faa-4632-a2b3-747aa00fe9c4','9f285bf7-46a1-4621-b165-dc782bf1d1ae',null,null,'ac45ebc4-f817-42e7-8d4a-96e41fb40ef8',null,null,1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('609f264b-1cef-4615-8f28-d8dae391dbba','com.valista.trxe.model.Transaction',1,to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed',null,'SETTLEMENT','CONFIRMED',to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',4,'USD',0,'9f285bf7-46a1-4621-b165-dc782bf1d1ae','1c887a16-4344-4a80-8a11-f26d80824e4a',null,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14','c0e866f2-0389-4fe3-9b11-f9ed6f49dd66','a2f09cbb-1555-4c8d-b401-0233982cfa7e','64103b9f-b760-4add-8c43-dbc7ac501fda',1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('3085c51d-6425-4974-b2fb-f5bdc4d08137','com.valista.trxe.model.Transaction',2,to_timestamp('15-AUG-11 12.31.23.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'testCharge',null,'PAYMENT','CONFIRMED',to_timestamp('15-AUG-11 12.31.23.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',10,'USD',0,'e8a58763-9faa-4632-a2b3-747aa00fe9c4','9f285bf7-46a1-4621-b165-dc782bf1d1ae',null,null,'db78d04e-c23d-4601-9b0e-76e826e85e29',null,null,1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('bafc4f83-d3b7-45f2-b35d-ba4101eebf3c','com.valista.trxe.model.Transaction',1,to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),'Settle: Payment Transaction Confirmed',null,'SETTLEMENT','CONFIRMED',to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',2,'USD',0,'9f285bf7-46a1-4621-b165-dc782bf1d1ae','1c887a16-4344-4a80-8a11-f26d80824e4a',null,'3085c51d-6425-4974-b2fb-f5bdc4d08137','9b5e384c-7ce9-4d7a-871e-5f418e737205','9c5cb90a-2035-490f-9ca7-c70f24a9010c','b70382c8-a05e-49c4-9919-ad765c5c5046',1,null,'TRUE');
Insert into TRANSACTION (TRANSACTION_ID,OBJECT_TYPE,VERSION,CREATED,LAST_UPDATED,DESCRIPTION,EXTERNAL_ID,TYPE,STATE,LAST_STATE_CHANGE,CHANNEL,MANDATE_ID,SUBSCRIPTION_ID,BULK_REFUND_TASK_ID,GROSS_CURRENCY,GROSS_AMOUNT,TAX_CURRENCY,TAX_AMOUNT,PAYER_ID,PAYEE_ID,ON_BEHALF_OF_PAYEE,ORIGINAL_ID,TRANSFER_ID,EVENT_ID,TERM_ID,CHARGE,TAGS_AND_VALUES,EXPORT_PENDING) values ('bbb6123b-8b70-45f2-b593-5b6bb2afd6b2','com.valista.trxe.model.Transaction',1,to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),'Correction: Payment Transaction Confirmed',null,'SETTLEMENT','CONFIRMED',to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),null,null,null,null,'USD',2,'USD',0,'1c887a16-4344-4a80-8a11-f26d80824e4a','9f285bf7-46a1-4621-b165-dc782bf1d1ae',null,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14','bef6cea1-d188-44e6-a5cf-6282480e13c2','a2f09cbb-1555-4c8d-b401-0233982cfa7e','e4a0bb0b-7273-4f28-8681-04fc067cb80d',1,null,'TRUE');
My Query
select transaction_id as trx_id,
last_updated,
nvl((case when payee_id= '9f285bf7-46a1-4621-b165-dc782bf1d1ae' then gross_amount end),0) as credit,
nvl((case when payer_id= '9f285bf7-46a1-4621-b165-dc782bf1d1ae' then gross_amount end),0) as debit,
connect_by_root transaction_id root,
rownum rn,
description as trx_desc
from (select * from transaction order by last_updated )
where type = 'SETTLEMENT'
start with original_id is null
connect by original_id = prior transaction_id order by last_updated
Result I got ( this is not a table just result set )
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('609f264b-1cef-4615-8f28-d8dae391dbba',to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),0,4,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',1,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('bbb6123b-8b70-45f2-b593-5b6bb2afd6b2',to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),2,0,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',2,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('c8ef1e7c-4134-45d8-9568-5da2fc41e137',to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,1,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',3,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('8243cc1d-614d-4cfd-9c3b-b5cd44b3a67f',to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),1,0,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',4,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('bafc4f83-d3b7-45f2-b35d-ba4101eebf3c',to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,2,'3085c51d-6425-4974-b2fb-f5bdc4d08137',5,'Settle: Payment Transaction Confirmed');
Result I want to get
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('609f264b-1cef-4615-8f28-d8dae391dbba',to_timestamp('15-AUG-11 10.17.43.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),0,4,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',1,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('bbb6123b-8b70-45f2-b593-5b6bb2afd6b2',to_timestamp('15-AUG-11 10.18.56.000000000 AM','DD-MON-RR HH.MI.SS.FF AM'),2,0,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',2,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('c8ef1e7c-4134-45d8-9568-5da2fc41e137',to_timestamp('15-AUG-11 12.01.42.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,1,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',3,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('8243cc1d-614d-4cfd-9c3b-b5cd44b3a67f',to_timestamp('15-AUG-11 12.29.45.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),1,0,'61db88ec-ade8-4cc3-90f3-e49fa26dcf14',4,'Correction: Payment Transaction Confirmed');
Insert into EXPORT_TABLE (TRX_ID,LAST_UPDATED,CREDIT,DEBIT,ROOT,RN,TRX_DESC) values ('bafc4f83-d3b7-45f2-b35d-ba4101eebf3c',to_timestamp('15-AUG-11 12.31.44.000000000 PM','DD-MON-RR HH.MI.SS.FF AM'),0,2,'3085c51d-6425-4974-b2fb-f5bdc4d08137',1,'Settle: Payment Transaction Confirmed');
Explanation
Refer 5th record of the result set. It has a RN = 5 and I want to get RN = 1 for that since that has a different ROOT and since it's the oldest memeber.
So Iwant to get RN as
date root row_number or something just find the oldest memeber in a tree
15-AUG-11 10.17.43.000000000 AM 61db88ec-ade8-4cc3-90f3-e49fa26dcf14 1
15-AUG-11 10.18.56.000000000 AM 61db88ec-ade8-4cc3-90f3-e49fa26dcf14 2
15-AUG-11 12.01.42.000000000 PM 61db88ec-ade8-4cc3-90f3-e49fa26dcf14 3
15-AUG-11 10.25.56.000000000 AM 55db88ec-ade8-4cc3-90f3-e49fa26dcf14 1
15-AUG-11 10.27.56.000000000 AM 55db88ec-ade8-4cc3-90f3-e49fa26dcf14 2
15-AUG-11 10.55.56.000000000 AM 85db88ec-ade8-4cc3-90f3-e49fa26dcf14 1 -
I have 3 table with the schema bellow
Student(Name,StuID,Class,Major)
Section (SectionID,CourseNum,Semester,year,instructor)
Grade(StuNo,SectioID,Grade)
Noe i want to query each section taught by Prof. King (Instructor name in section table) , reterive the courseNum, year, and the number of students who took the section.
I tires follwoing query
select coursenumber,semester,year,count(*)
from section x, grade_report y
where x.SectionIdentifier = y.SectionIdentifier AND instructor = 'King'
group by y.SectionIdentifier;
but i am getting the follwoing error
select coursenumber,semester,year,count(*)
ERROR at line 1:
ORA-00979: not a GROUP BY expression
I removed the count(*) and group by function and quiried the StuNo, then i am getting the record. How can i count the actual students who took the section.
ThanksI recommend you to post this as well here:
Forums Home » Oracle Technology Network (OTN) » Products » Database » SQL and PL/SQL
Discussion of Oracle SQL and PL/SQL issues
PL/SQL
Joel Pèrez -
Hi expert
I have a table with the column FIRST and LAST as per example
>
FIRST;LAST
FIRST1;LAST1
FIRST2;LAST2
FIRST3;LAST3
FIRST4;LAST4
FIRST5;LAST5
FIRST6;LAST6
FIRST7;LAST7
FIRST8;LAST8
FIRST9;LAST9
FIRST10;LAST10
FIRST11;LAST11
FIRST12;LAST12
>
I'd like to do an sql that create the value of column ID with a "group by" by 5 records. For example from 1 to 5 the ID will be 1, from 6 to 10 the ID will be 2. Below the result that I'd to do
>
ID;FIRST;LAST
1;FIRST1;LAST1
1;FIRST2;LAST2
1;FIRST3;LAST3
1;FIRST4;LAST4
1;FIRST5;LAST5
2;FIRST6;LAST6
2;FIRST7;LAST7
2;FIRST8;LAST8
2;FIRST9;LAST9
2;FIRST10;LAST10
;FIRST11;LAST11
;FIRST12;LAST12
>
The last 2 records will not a ID because the count of them is less of 5.
Many thanks for any idea.
Cheers,
LainOr like this...
SQL> ed
Wrote file afiedt.buf
1 with t as (select 'FIRST1' as FIRST, 'LAST1' as LAST from dual union all
2 select 'FIRST2', 'LAST2' from dual union all
3 select 'FIRST3', 'LAST3' from dual union all
4 select 'FIRST4', 'LAST4' from dual union all
5 select 'FIRST5', 'LAST5' from dual union all
6 select 'FIRST6', 'LAST6' from dual union all
7 select 'FIRST7', 'LAST7' from dual union all
8 select 'FIRST8', 'LAST8' from dual union all
9 select 'FIRST9', 'LAST9' from dual union all
10 select 'FIRST10', 'LAST10' from dual union all
11 select 'FIRST11', 'LAST11' from dual union all
12 select 'FIRST12', 'LAST12' from dual)
13 --
14 -- End Of Test Data
15 --
16 select decode(count(*) over (partition by id), 5, id) as id
17 ,first
18 ,last
19 from (
20 select floor((row_number() over (order by ord)-1)/5)+1 as id
21 ,first
22 ,last
23 ,ord
24 from (select first, last, to_number(replace(first,'FIRST')) ord from t)
25 )
26* order by ord
SQL> /
ID FIRST LAST
1 FIRST1 LAST1
1 FIRST2 LAST2
1 FIRST3 LAST3
1 FIRST4 LAST4
1 FIRST5 LAST5
2 FIRST6 LAST6
2 FIRST7 LAST7
2 FIRST8 LAST8
2 FIRST9 LAST9
2 FIRST10 LAST10
FIRST11 LAST11
FIRST12 LAST12
12 rows selected.
SQL>Though, I assume your data is not "FIRST1", "FIRST2" etc., so the ordering of the data will have to be done according to what data you have. In my solution I've stripped out the word "FIRST" to allow it to be ordered on the numeric part of the data. I assume you've got some other data there to allow you to determine the order though. -
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 -
SQL - Group By / Order by question
I have a table MESSAGE with two columns.
SQL> desc message
Name Null? Type
MESSAGE_TEXT VARCHAR2(50)
MESSAGE_DATE DATE
My requirements are:
1) Display MESSAGE_TEXT and MESSAGE_DATE (Date only, no time component) in MESSAGE_DATE order (including time component).
2) Do not show multiple rows which have the same MESSAGE_TEXT and trunc(MESSAGE_DATE).
Given the following data:
SQL> select * from message;
MESSAGE_TEXT MESSAGE_DATE
Message Group 1 10/15/2002 13:00:00
Message Group 1 10/15/2002 14:00:00
Message Group 1 10/16/2002 15:00:00
Message Group 2 10/15/2002 14:00:00
Message Group 2 10/15/2002 16:00:00
Message Group 3 10/15/2002 13:30:00
Message Group 3 10/15/2002 17:00:00
I should return:
MESSAGE_TEXT MESSAGE_DATE
Message Group 1 10/15/2002
Message Group 3 10/15/2002
Message Group 2 10/15/2002
Message Group 1 10/16/2002
My first attempt to do this was:
SELECT MESSAGE_TEXT
, TO_CHAR(MESSAGE_DATE,'MM/DD/YYYY') FDATE
FROM MESSAGE
GROUP BY MESSAGE_TEXT, TO_CHAR(MESSAGE_DATE,'MM/DD/YYYY')
ORDER BY FDATE
but this did not work because it returned:
MESSAGE_TEXT FDATE
Message Group 1 10/15/2002
Message Group 2 10/15/2002
Message Group 3 10/15/2002
Message Group 1 10/16/2002
which violates requirement 1). Message Group 3 should appear before Message Group 2 because 13:30 comes before 14:00.
I ended up doing the following:
SELECT MESSAGE_TEXT
, TO_CHAR(MESSAGE_DATE,'MM/DD/YYYY') FDATE
FROM MESSAGE M1
WHERE NOT EXISTS
(SELECT *
FROM MESSAGE M2
WHERE M2.MESSAGE_TEXT = M1.MESSAGE_TEXT
AND TRUNC(M2.MESSAGE_DATE) = TRUNC(M1.MESSAGE_DATE)
AND M2.MESSAGE_DATE < M1.MESSAGE_DATE)
ORDER BY M1.MESSAGE_DATE
This gives me the right results, but surely there is a better way or ways. Please help.SELECT message_text,
message_date_only AS message_date
FROM (SELECT message_text,
TO_CHAR (message_date, 'MM/DD/YYYY') AS message_date_only,
MIN (message_date) AS min_message_date_and_time
FROM message
GROUP BY message_text, TO_CHAR (message_date, 'MM/DD/YYYY'))
ORDER BY min_message_date_and_time;
MESSAGE_TEXT MESSAGE_DATE
Message Group 1 10/15/2002
Message Group 3 10/15/2002
Message Group 2 10/15/2002
Message Group 1 10/16/2002
4 rows selected. -
Hi All
I am new to SQL .
There are two tables EMP and DEPT . The common column betwee these two is DEPT_NO
Al I am trying to do is display the department name , number of employees and the department's average salary of the employees.
Below id my query . I am not able to complete the query due to the issues that group by clause poses .
Could some one please help ?
SELECT DEPT.DEPT_NAME , SUM(EMP.EMP_NO) , AVG(EMP.SAL)
FROM EMP , DEPT
WHERE EMP.DEPT_NO = DEPT.DEPT_NO
GROUP BY DEPT.DEPT_NAME
Thanks
Gunauser9967723 wrote:
I want to display the employee name, department number, and all the employees that work in the same department .This seems very different from your original request.
Also please let me know where i can find a 'attachment link in this page' to attach the table snap shot. You cannot attach anything in this forum. Creating a text version would be the most helpful as some external sites that host images are blocked for some of the users here.
It is always helpful to provide the following:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
Also see the third post in this thread:
{thread:id=2174552} -
SQL - Group by fixed hours twice daily
Hi All,
I have a requirement to produce a status report daily on 2 fixed intervals for the past 4 days.
For example, # of products sold at 6PM & 6AM for past 4 days...
results should look like:
DATE PRODUCT_NAME Count(*)
8/29/2012 6 AM PROD_01 50
8/28/2012 6 PM PROD_01 32
8/28/2012 6 AM PROD_01 55
8/27/2012 6 PM PROD_01 44
select trunc(mydate)+6/24, product, count(*)
where mydate > sysdate - 4
and ....
group by
trunc(mydate)+6/24, product
This gives me 6AM every day... how to include 6PM also in this sql.
I am looking for help in grouping based on two fixed time intervals in a day.
Edited by: user2144930 on Aug 29, 2012 11:49 AMHi,
Welcome to the forum!
So you want every row assigned to a group: one group lasts from
6:00 PM on August 28 to 6:00 AM on Augsut 29, and the next group goes from
6:00 AM on August 29 to 6:00 PM on August 29. Is that it?
Here's one way to do that, withou using UNION:
WITH got_period_start AS
SELECT product
, mydate
, TO_CHAR ( mydate - (6 / 24)
, 'DD-Mon-YYYY "6:00" AM'
) AS period_start
FROM table_x
WHERE mydate >= SYSDATE - 4
AND mydate < SYSDATE -- If necessary
AND ... -- other filtering, if needed
SELECT product
, period_start
, COUNT (*) AS cnt
FROM got_period_start
GROUP BY product
, period_start
ORDER BY product
, MIN (mydate) -- since period_start is a VARCHAR2, and may not be good for sorting
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
See the forum FAQ {message:id=9360002} -
Sql grouping and summing impossible?
I want to create an sql query to sum up some data but i'm starting to think it is impossible with sql alone. The data i have are of the following form :
TRAN_DT TRAN_RS DEBT CRED
10-Jan 701 100 0
20-Jan 701 150 0
21-Jan 701 250 0
22-Jan 705 0 500
23-Jan 571 100 0
24-Jan 571 50 0
25-Jan 701 50 0
26-Jan 701 20 0
27-Jan 705 0 300The data are ordered by TRAN_DT and then by TRAN_RS. Tha grouping and summing of data based on tran_rs but only when it changes. So in the table above i do not want to see all 3 first recods but only one with value DEBT the sum of those 3 i.e. 100+150+250=500. So the above table after grouping would be like the one below:
TRAN_DT TRAN_RS DEBT CRED
21-Jan 701 500 0
22-Jan 705 0 500
24-Jan 571 150 0
26-Jan 701 70 0
27-Jan 705 0 300The TRAN_DT is the last value of the summed records. I undestand that the tran_dt may not be selectable. What i have tried so far is the following query:
select tran_dt,
tran_rs,
sum(debt)over(partition by tran_rs order by tran_dt rows unbounded preceding),
sum(cred)over(partition by tran_rs order by tran_dt rows unbounded preceding) from that_tableIs this even possible with sql alone, any thoughts?
The report i am trying to create in BI Publisher.Maybe it is possible to group the data in the template and ask my question there?915218 wrote:
Is this even possible with sql alone, any thoughts?It sure is...
WITH that_table as (select to_date('10/01/2012', 'dd/mm/yyyy') tran_dt, 701 tran_rs, 100 debt, 0 cred from dual union all
select to_date('20/01/2012', 'dd/mm/yyyy') tran_dt, 701 tran_rs, 150 debt, 0 cred from dual union all
select to_date('21/01/2012', 'dd/mm/yyyy') tran_dt, 701 tran_rs, 250 debt, 0 cred from dual union all
select to_date('22/01/2012', 'dd/mm/yyyy') tran_dt, 705 tran_rs, 0 debt, 500 cred from dual union all
select to_date('23/01/2012', 'dd/mm/yyyy') tran_dt, 571 tran_rs, 100 debt, 0 cred from dual union all
select to_date('24/01/2012', 'dd/mm/yyyy') tran_dt, 571 tran_rs, 50 debt, 0 cred from dual union all
select to_date('25/01/2012', 'dd/mm/yyyy') tran_dt, 701 tran_rs, 50 debt, 0 cred from dual union all
select to_date('26/01/2012', 'dd/mm/yyyy') tran_dt, 701 tran_rs, 20 debt, 0 cred from dual union all
select to_date('27/01/2012', 'dd/mm/yyyy') tran_dt, 705 tran_rs, 0 debt, 300 cred from dual)
, brk AS (
SELECT tran_dt,
tran_rs,
debt,
cred,
CASE WHEN Nvl (Lag (tran_rs) OVER (ORDER BY tran_dt, tran_rs), 0) != tran_rs THEN tran_rs || tran_dt END brk_tran_rs
FROM that_table
), grp AS (
SELECT tran_dt,
tran_rs,
debt,
cred,
Last_Value (brk_tran_rs IGNORE NULLS) OVER (ORDER BY tran_dt, tran_rs) grp_tran_rs
FROM brk
SELECT Max (tran_dt),
Max (tran_rs),
Sum (debt),
Sum (cred)
FROM grp
GROUP BY grp_tran_rs
ORDER BY 1, 2
Boneist
MAX(TRAN_ TRAN_RS DEBT CRED
21-JAN-12 701 500 0
22-JAN-12 705 0 500
24-JAN-12 571 150 0
26-JAN-12 701 70 0
27-JAN-12 705 0 300
Me
MAX(TRAN_ MAX(TRAN_RS) SUM(DEBT) SUM(CRED)
21-JAN-12 701 500 0
22-JAN-12 705 0 500
24-JAN-12 571 150 0
26-JAN-12 701 70 0
27-JAN-12 705 0 300Edited by: BrendanP on 17-Feb-2012 04:05
Test data courtesy of Boneist, and fixed bug.
Edited by: BrendanP on 17-Feb-2012 04:29 -
Use of sql group function in orcl:query-database - urgent
All,
Version: 10.1.3.4
Two requirements for me:
1. I want to use sum function in orcl:query-database. How to use it?
For ex: I tried the following
<xsl:value-of select='orcl:query-database("select sum(salary) from emp",false(),false(),"jdbc/DB1")'/>
I got the following error
oracle.xml.sql.OracleXMLSQLException: Character ')' is not allowed in an XML tag name.
When I tried without sum function, it works fine
2. I used the same table, but without the sum function as below
<xsl:value-of select='orcl:query-database("select salary from emp",false(),false(),"jdbc/DB1")'/>
This time, it returns the first employees salary!! I dont understand this logic. I expected either the query returns all the rows else it throws error, but none of them were true!
Can anyone pls explain what is the behavior? I want your reply for both the queries!
Currently I'm in a project where I'm working in the similar scenario, so please guru's let me know ASAP.
Thanks,
SenHi Sen,
Create a normal variable variable in XSLT.
Then use that variable.
I mean variable name='Var_1' select='Your Query'
Now use Var_1/yourcollection/...
I am giving some example
<xsl:variable name="Stopdetails" select="/ns0:MyEBM/ns0:DataArea/ns0:MyEBO/ns0:Stops/ns0:Stop[ns0:StopID=$TempStopId]"/>
<xsl:variable name="AccStopTypeVar">
<xsl:value-of select="$Stopdetails/ns0:StopType"/>
</xsl:variable>If you want you can loop on the created variable.
You can do these in XSL.
But DB calls those things ...it would be better , if u take them out. Spme debugging problems are there with XSL.
Regards
PavanKumar.M
Maybe you are looking for
-
Very slow BB speed for 3 months.
Hello. We have been with BT for I think more than 4 years and never had a problem. That is until early October this year. The first night I had constant disconnections out of no where. About a week later I started having huge lag spikes, mostly when
-
Hi everybody. I am new to this forum but I have been a Creative user for a long time. My question is this I just bought a new 8gb Zen and the software that came with it did not include the Creative Mediasource organizer. I love the mediasource organi
-
My 4 hours w/ AT&T Captivate..Be happy with your X!
I spent the afternoon today using a brand new Samsung Captivate Galaxy S phone, on AT&T in the Boston Area. My friend from work recieved the phone today, charged it and asked me to use it for the day and "make it like mine". My impressions are ba
-
I want to make changes to a TV viewer swf file by changing the color scheme in the corresponding CSS file. I was told to compile the file when the changes are made in the CSS file. Question: Do I compile the SWF file itself. Can someone give me some
-
Manage downloads in itunes. Where do I find this?
Help I downloaded a movie and it will not play. When I hit the cloud icon it tells me this movie was purchased but not downloaded and to go to manage my downloads to finish downloading where do I find this? I saw a download icon when I originally dow