Using a SQL Query Group by is needed
Hi All,
Scenario Below:
we have 2 Transactions, 5 Lines and each line is having 2 Taxes correspondingly. We have few more formula columns which are calculating based on requirements.
We need to Group the amount at Line level for the one specific TAX.
say: L1 1, L2 2, L3 3, L4 4, L5 5. for one tax having L1, L2 and L3 which needs to be sum up 6
and for other tax needs to sum up to 9.
But, we need to display all the Lines.
Regards,
Reddy.
Hi, Reddy,
Use the analytic SUM function instead of the aggregate function if you don't want to get only one line of output per group.
Since I don't have a copy of your table, I'll use the scott.emp table to illustrate.
The following query gets some information about individual employees, along with the total salary of all the employees with the same job:
SELECT job
, ename
, sal
, SUM (sal) OVER (PARTITION BY job) AS total_sal
FROM scott.emp
ORDER BY job
;Output:
JOB ENAME SAL TOTAL_SAL
ANALYST SCOTT 3000 6000
ANALYST FORD 3000 6000
CLERK MILLER 1300 4150
CLERK JAMES 950 4150
CLERK SMITH 800 4150
CLERK ADAMS 1100 4150
MANAGER BLAKE 2850 8275
MANAGER JONES 2975 8275
MANAGER CLARK 2450 8275
PRESIDENT KING 5000 5000
SALESMAN TURNER 1500 5600
SALESMAN MARTIN 1250 5600
SALESMAN WARD 1250 5600
SALESMAN ALLEN 1600 5600Almost all of the aggregate functions (including SUM, AVG, COUNT, MIN, even user-defined aggregate functions like STRAGG) have analytic counterparts. The keyword OVER after the argument list marks the function as analytic.
The analytic PARTITION BY clause corresponds to the aggregate GROUP BY.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
It never hurts to say what version of Oracle you're using.
Similar Messages
-
XML Generation using a sql query in an efficient way -Help needed urgently
Hi
I am facing the following issue while generating xml using an sql query. I get the below given table using a query.
CODE ID MARK
==================================
1 4 2331 809
2 4 1772 802
3 4 2331 845
4 5 2331 804
5 5 2331 800
6 5 2210 801
I need to generate the below given xml using a query
<data>
<CODE>4</CODE>
<IDS>
<ID>2331</ID>
<ID>1772</ID>
</IDS>
<MARKS>
<MARK>809</MARK>
<MARK>802</MARK>
<MARK>845</MARK>
</MARKS>
</data>
<data>
<CODE>5</CODE>
<IDS>
<ID>2331</ID>
<ID>2210</ID>
</IDS>
<MARKS>
<MARK>804</MARK>
<MARK>800</MARK>
<MARK>801</MARK>
</MARKS>
</data>
Can anyone help me with some idea to generate the above given CLOB messagenot sure if this is the right way to do it but
/* Formatted on 10/12/2011 12:52:28 PM (QP5 v5.149.1003.31008) */
WITH data AS (SELECT 4 code, 2331 id, 809 mark FROM DUAL
UNION
SELECT 4, 1772, 802 FROM DUAL
UNION
SELECT 4, 2331, 845 FROM DUAL
UNION
SELECT 5, 2331, 804 FROM DUAL
UNION
SELECT 5, 2331, 800 FROM DUAL
UNION
SELECT 5, 2210, 801 FROM DUAL)
SELECT TO_CLOB (
'<DATA>'
|| listagg (xml, '</DATA><DATA>') WITHIN GROUP (ORDER BY xml)
|| '</DATA>')
xml
FROM ( SELECT '<CODE>'
|| code
|| '</CODE><IDS><ID>'
|| LISTAGG (id, '</ID><ID>') WITHIN GROUP (ORDER BY id)
|| '</ID><IDS><MARKS><MARK>'
|| LISTAGG (mark, '</MARK><MARK>') WITHIN GROUP (ORDER BY id)
|| '</MARK></MARKS>'
xml
FROM data
GROUP BY code) -
Using a SQL Query in an Alert and Matching a String
I've created an alert in 12.0.4 using a SQL Query and the field that I'm trying to match is a string. Originally the query returned multiple rows but when the alert still didn't fire, I modified the query WHERE clause to return only one row:
NAME RESPONSE
Are area lights working? No
My expression in the metric is RESPONSE. In the Monitor I'm matching a string equal to No. (Do I need double quotes around the matchvalue? Single quotes? No quotes?) The metric is in the 15min scan group, the role is xMII Developers and I'm in that role. The monitor alert string is ' = '. Both metric and monitor are active and I've subscribed to the monitor. Other alerts in the 15min scan group (all based on tag queries) are firing off properly.
Why is nothing showing up in the Alert Log?
David MacindoeDavid,
Did you figure out the answer? If not, I will try to find someone to address your question.
Mike -
Can we use Data Pump to export data, using a SQL query, doing a join
Folks,
I have a quick question.
Using Oracle 10g R2 on Solaris 10.
Can Data Pump be used to export data, using a SQL query which is doing a join between 3 tables ?
Thanks,
AshishHello,
No , this is from expdp help=Y
QUERY Predicate clause used to export a subset of a table.
Regards -
How to use this sql query in oracle?
Hi all,
i am using one sql query that is
SELECT @ToDate = '2012-10-03 00:00:00.000'
select @BetweenDate = DATEADD(MM,-1,@ToDate)
select @FromDate = DATEADD(m,DATEDIFF(m,0,@BetweenDate),0)
SELECT @ToDate = DATEADD(month, ((YEAR(@BetweenDate) - 1900) * 12) + MONTH(@BetweenDate), -1)
so @todate value is = '2012-10-03 00:00:00.000'
so in @betweendate value will come 1 month before like '2012-09-03 00:00:00.000'
again in @fromdate value will come like that '2012-09-01 00:00:00.000' means first date of @betweendate
and again @todate value will come like that '2012-09-30 00:00:00.000' means last date of @betweendate
it's happening in sql and i have to use same logic in oracle also.
how to use it??
thanksdeclare
todate date:= to_date('2012-10-03 00:00:00','yyyy-mm-dd hh:mi:ss');
betwendate date := add_months(todate,-1);
for datediff / additions you can direct subtract/add two different date variables
like
datediff = betweendate -todate
dateadd := todate+1; -
Hi,
I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work
(fault number -2147217900)
I want to search for a value in a ms access table , if it exist i want to update it, if not i want to insert a new row.
Working with LabView 7.1, database con. toolset.
Who can HELP?
Thanks a lot
MarcoHello,
I think that If exist is not a standar SQL command (I know it exists I think in Oracle and SQL server), MS access doesn't support it, so I think the best way to do it is first make a Select and then either an Update or an insert, sorry...
Paulo -
Im writing a jsp that pulls data from the database and loads it into dropdown-list looks like this:
<select name="Source">
<%
conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT BBCourseID(Sroffer.SrofferID)course_name, SrofferSchedule_Faculty.FacultyID AS FacultyID FROM SrofferSchedule_Faculty srofs JOIN SrofferScheduleID sros ON srofs.SrofferScheduleID= sro.SrofferScheduleID JOIN Sroffer sro ON sro.SrofferID= sros.SrofferID WHERE srofs.FacultyID=IDnumber");
rs.beforeFirst();
while (rs.next()) {%>
<option value="<%=courseid=rs.getString("BBCourseID")%>"><%=courseid%> <%=rs.getString("course_name")%></option>
<%}
%>
</select>
Problem is, I have to pull the FacultyID from cams using this sql query
("SELECT FacultyID FROM FacultyPortal WHERE PortalAlias="") berfore i can run the query above. Don't know how to do this in a jsp
Edited by: JohnsonJ on Mar 26, 2009 5:53 PMYou know how to get a connection and how to execute a query and how to process the resultset - so what's standing in your way of doing that for the faculty ID?
Isn't there a join you can do to get that in one query?
And finally - you really shouldn't do this in a JSP, use a servlet to package the result up in some Java Collection and process it with JSTL tags. -
Is there a way to consolidate calculations used in SQL Query Data Sets?
I am building SQL Query Data Sets against multiple DB Views which all have different date formats. I have the date parameter working well, but want to consolidate the changes that I have to do to it especially for the quarter. For example the SQL against a monthly view would use "where year_month > to_char(:ST_DATE, 'YYYY-MM')" which is not too hard, but to make that work for the quarterly view I need several concats and a decode to get a "> '2012-Q2'". I would like not to have to do this within every where clause. I had put this into a global element hoping to use that in a filter for the data set, but the filter does not have access to global elements only parameters.
Is there any way to refer to a calculated global element from the data set to do this? I am using Layout Templates, so even if I wanted to I could not do the condition within the template.
Thanks,
RickChange the following line to include the red coloured parts
<div class="MasterColumn" spry:repeat="ds4" spry:setrow="ds4" spry:hover="MasterColumnHover" spry:select="MasterColumnSelected">
<span>{Dsp_#}</span><span>{Dsp_WkDay}</span><span>{Dsp_Event}</span>
</div>
The add the following style rule to your document:
.MasterColumn span {
display: inline-block;
I hope this helps.
Ben -
Use an SQL Query in a backing bean
hi,
I like to know how to run an SQL query in a backing bean method, this being the code I tried , his goal is to fill the field "cin" with data coming from my database, here is the Code:
public String cb2_action() {
BindingContainer bindings = getBindings();
OperationBinding operationBinding = bindings.getOperationBinding("CreateInsert");
Object result = operationBinding.execute();
if (!operationBinding.getErrors().isEmpty()) {
return null;
DCIteratorBinding dciter =(DCIteratorBinding) bindings.get("PersonneView1Iterator");
Row row=dciter.getCurrentRow();
Statement stmt = this.getDBTransaction().createStatement(1);
try {
ResultSet rs = stmt.executeQuery("select max(cin) from personne");
while( rs.next() ){
row.setAttribute("cin", rs.getInt(1)+1);
} catch (SQLException ex) {
ex.printStackTrace();
return "go";
at run time it give an error at this line : Statement stmt = this.getDBTransaction().createStatement(1);
please check and correct me
thanks in advanceHi,
Initially I would like to say that this should not be used if you are trying to get a PrimaryKey as it would cause serious concurrency issues.
For example lets say that you want whenever you create a new Employee to set his DepartmentId equal to the max department.
We could create a readOnly VO (lets name it MaxDepartmentId) with a query that returns the max departmentId:
select max(Department_Id) as maxDep from DepartmentsAfter that we need to add the MaxDepartmentId VO as a ViewAccessor in our Employees Vo,
override the create() method in the EmployeesRowImpl and add some code like this:
public class EmployeesRowImpl extends ViewRowImpl {
@Override
protected void create(AttributeList attributeList) {
Row r=getMaxDepartmentId().first();
if(r!=null){
Number max=(Number)r.getAttribute("Maxdep");
attributeList.setAttribute("DepartmentId", max);
super.create(attributeList);
}That's all.
If you run this you will see that when you create a new employee it has a default value.
Gabriel. -
How do I pull SharePoint 2013 list data using a SQL Query
I have been asked to write a sql query to pull data from a SharePoint 2013 List.it needs to return all the columns
Basically a Select all from the specific SharePoint list Database
I do have the list GUID ID. But not sure which SQL Table or Database to look in for list data.. the site and the list is in our main SharePoint site collection.
the query only needs to be saved in SQL serverI know it isn't support but sometimes you have to share data with other programs....
I'm stuck.. I was able to get this far...
SELECT * FROM dbo.Lists
where tp_Title ='List Name'
how do I pull the columns of the list?
I think I still need the specific list not just the master list dbo....
those two links do not work for SQL server and SharePoint 2013 -
Check the hints used in SQL Query (Parallel, First_Rows)
Hi,
I have used above hints in my sql query and found no difference in execution time.
I just want to know whether the hints are used in my sql are not.
Could you please let me know where to check for it.
Thanks in advanceCan you post the SQL which uses these hints and the execution plan with and without those hints here? Then only community can help you find out if the hints are really used or not.
Please use code tags to preserve the format of execution plan.
Edited by: Satish Kandi on Jun 23, 2009 5:37 PM -
How to find a dependent row in the all tables using single SQL query
hi all,
I have created some table with master and some dependent tables.I want to mark a (row)tuple as inactive in master so that corresponding child records also should be marked as inactive.
So i decided to mark the master and dependent records as inactive starting from master table and traverse to child tables.
So I need SQL query to fetch all dependend records to the row(marked row in the master ) from the master table and dependent rows from the child row and to mark as flag inactive.
can anybody help me out to build this query or any other way to mark flag as inactive ?
Regards
punithanYou can find dependant tables from ALL_CONSTRAINTS, e.g:
SQL> CREATE TABLE m (id INT PRIMARY KEY, flag VARCHAR2(1) NOT NULL);
Table created.
SQL> CREATE TABLE d1 (m_id REFERENCES m, flag VARCHAR2(1) NOT NULL);
Table created.
SQL> CREATE TABLE d2 (m_id REFERENCES m, flag VARCHAR2(1) NOT NULL);
Table created.
SQL> SELECT table_name, owner, status
2 FROM all_constraints c
3 WHERE c.constraint_type = 'R'
4 AND ( c.r_owner, c.r_constraint_name ) IN
5 ( SELECT owner, constraint_name
6 FROM user_constraints
7 WHERE table_name = 'M'
8 AND constraint_type IN ('U','P') );
TABLE_NAME OWNER STATUS
D2 WILLIAMR ENABLED
D1 WILLIAMR ENABLED
2 rows selected.There is no SQL command to apply all updates in one go, if that's what you were looking for.
AFAIK the word "tuple" is for mathematics and relational theory, and does not refer to a physical row in a database. -
How to create a Folder using a SQL Query?
Hi
How can I create a Folder (eg. C:\MyNewFolder) using SQL Query?Hi,
I added some code in order to get the result from the xp_cmdshell command
This returns null if successfull, if an error occurs returns the error message. May be useful instead of getting an sql error
Code Snippet
declare @cmdpath nvarchar(60), @Location nvarchar(100), @message nvarchar(max)
set @Location = N'C:\Temp\Temp5'
set @cmdpath = 'MD '+ @Location
Create table #result
result nvarchar(255)
insert into #result (result) exec master.dbo.xp_cmdshell @cmdpath
select @message = ISNULL(@message + ' - ','') + result from #result where result is not null
select @message
drop table #result
Eralper
http://www.kodyaz.com -
SQLEception using Complex SQL Query with Java Studio Creator2 Build(060120)
I am evaluating Java Studio Creator2 for a WEB base application project that will be making SQL queries to an Oracle Database but I have stumble into a problem using complex SQL queries.
I am getting an SQLException "org.apache.jasper.JasperException: java.lang.RuntimeException: java.sql.SQLException: [sunm][Oracle JDBC Driver][Oracle]ORA-00923: FROM keyword not found where expected". I looks like it cut my sql.
The SQL that I am trying to execute is
Select part_name
from table1, table2
where table1.part_nbr = table2.part_nbr
and table2.row_add_dt = (select max(table3.row_add_dt)
from table3
where table3.ser_part_id =table2.ser_part_id)
This is a valid query that it is using 2 different selects to get a part number.
If posible, point me to the best solution were I will be able to make complex SQL queries like the one above and bigger.
Is there any way that I can read an SQL query file instead of inserting the SQL query string into the setCommand()?I have read that document looking for some anwsers on how to make this kind of query. If I try the query that I have above in the query editor ,the query editor will cut off from the last select that is between ().
I beleave, there is a work around using the inner joint or outter join command. I will try them to see If I get the corrent result. If not, then I have to keep on asking for possible solutions.
Anyway, someone in the Creator Team should take a note in adding something like a special criteria in the Add Query Criteria Box for cases like the one I have. The special criteria will be like using another select/from/where to get some result that will be compare.
Girish, Are you in the Sun Creator Team? -
Report in Answers using a SQL Query(Sub Query) URGENT
HI
Can anyone help me in creating a report in answers using this below query please. Its little Urgent. I have no idea how to implement this, please suggest.
Select
a.account_external_id, a.edc_external_id, c.ann_usg, indclassificationcode, g.usage_cv, trunc(g.bill_month, 'mm') bill_month
from
crm2ro.cdi_customer_gas_all a, pwrline.account@lodestar_source b, crm2ro.cdi_ann_usg c,
select * FROM
select * from
select distinct d.account_external_id, d.end_date, d.bill_month, USAGE_CV, dense_rank () over (partition by d.account_external_id order by d.end_Date desc) dr
from
crm2ro.cdi_usage_gas_all d, crm2ro.cdi_customer_gas_all e
where
d.account_external_id = e.account_external_id and upper(e.plan_id) like '%CPS%' and e.product_external_id = 'V' and e.crm_product = 'MV'
and (e.plan_id like '%VAR_CPS_MX_G%' or e.plan_id like '%VAR_CPS_IT_G%') and e.account_status = 'ACTIVE'
)where dr<=12
) h
) g
where
a.account_external_id = g.account_external_id and
a.account_external_id = c.account_external_id and
a.account_external_id = b.accountid
thanks
vanYes Jai,
I want to do it from rpd or from the advance tab as 974053 said. But I am not aware of doing through advance tab and if I want to do through rpd then how can I do it. Please help me how to build this query through rpd or any other solution.
Maybe you are looking for
-
Adding new date field to already loaded data target.
Hi, we have a cube containing date feild such as 0CALMONTH. the data is being loaded to the cube. now they have added new date feild (0FISCYEAR). how to get data to this feild. there is no data coming from source system for this feild. please can
-
This is not a rant, but I'm puzzled. I've always accessed Adobe's groups via NNTP, but the PE Tech Issues group seems only to be on the webbish forums and not on the news server. I only see .featurerequests and .organizer on NNTP, even after deleting
-
Need help in date conversion(it's Urgent)
I am reading data from the text file... and inserting that data into the oracle table(using bpel process) I have following problem with the date field. In the XSD file if i specify the date format as nxsd:dateFormat="ddMMyyyy" and when i pass null va
-
I am getting following errors "errors were retryable:
I have out putted the following but have no idea what to do. I am thinking it might be a hba, fiber cable or hhd on storage. root@xxxxxzner01p-gz[~]# dmesg Monday, May 7, 2012 2:14:38 PM EDT May 7 13:14:33 xxxxxzner01p-gz scsi: [ID 107833 kern.notice
-
Resizing/fading dynamic gallery issues...
Hey there. I'm kind of in a huge deadline crunch. I have a gallery that I built from a tutorial I found online--it has an empty mc with a border around it, and when you click on a thumbnail an image is loaded into the mc and it fades in when it loads