Conditional GROUP BY clause
Hi,
I have four columns in group by clause. I want to add conditional group by clause.
Case 1 : If one of the column's value is null, I don't want to include it in group by clause. Means, Now GROUP BY clause will have only 3 columns.
Case 2 : If not null, then GROUP BY clause with all four columns.
Please help me out on this.
Thanks in advance.
Hi
I think it won't matter, all group functions by default ignore NULLs so your result won't differ.
select dept, loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
group by dept,loc;
Output
DEPT LOC SUM(SAL)
1 P 300
2 P 700
3 P 1100
Q 3300
4 Q 700
Now by doing grouping only for NOT NULL values,
select dept,loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
where dept is not null --------------NOT NULL Condition
group by dept, loc;
Output
DEPT LOC SUM(SAL)
1 P 300
2 P 700
3 P 1100
4 Q 700
Now by doing grouping only for NULL values,
select dept,loc, sum(sal)
from (
select 'A' emp , 1 dept , 'P' loc , 100 sal from dual union all
select'B',1,'P',200 from dual union all
select'C',2,'P',300 from dual union all
select'D',2,'P',400 from dual union all
select'E',3, 'P',500 from dual union all
select'F',3, 'P',600 from dual union all
select'G',4, 'Q',700 from dual union all
select'H', null,'Q' , 1000 from dual union all
select'I',null ,'Q', 2000 from dual union all
select 'J' ,null, 'Q',300 from dual)
where dept is null --------------NULL Condition
group by dept, loc;
Output
DEPT LOC SUM(SAL)
Q 3300
The output is same for both the conditions.
Similar Messages
-
Hi
I need a SQL report to conditionally display fields based on the value of a bind variable.
I can achieve this via the interactive reports feature conditional display but I need to remove the GROUP BY for that field at the same time.
How can I have a conditional GROUP BY clause based a value of a bind variable?
Regards
Adam>
If :SHOW_FIELD3 was NOT 'TRUE' then what would
the statement GROUP BY??? ...The statement would group by field1 and field2 in that case.
test@ora>
test@ora> var FIELD1_SHOW varchar2(5)
test@ora> var FIELD2_SHOW varchar2(5)
test@ora> var FIELD3_SHOW varchar2(5)
test@ora>
test@ora> exec :FIELD1_SHOW := 'TRUE';
PL/SQL procedure successfully completed.
test@ora> exec :FIELD2_SHOW := 'TRUE';
PL/SQL procedure successfully completed.
test@ora> exec :FIELD3_SHOW := 'FALSE';
PL/SQL procedure successfully completed.
test@ora>
test@ora> --
test@ora> with t as (
2 select 'true' as f1, 'true' as f2, 'true' as f3, 1 as num from dual union all
3 select 'true', 'true', 'true', 2 from dual union all
4 select 'true', 'false', 'true', 9 from dual union all
5 select 'true', 'false', 'true', 10 from dual union all
6 select 'true', 'true', 'false', 20 from dual union all
7 select 'true', 'true', 'false', 21 from dual)
8 --
9 select
10 decode(:FIELD1_SHOW, 'TRUE', f1) as f1,
11 decode(:FIELD2_SHOW, 'TRUE', f2) as f2,
12 decode(:FIELD3_SHOW, 'TRUE', f3) as f3,
13 sum(num) as total
14 from t
15 group by decode(:FIELD1_SHOW, 'TRUE', f1),
16 decode(:FIELD2_SHOW, 'TRUE', f2),
17 decode(:FIELD3_SHOW, 'TRUE', f3);
F1 F2 F3 TOTAL
true false 19
true true 44
test@ora>
test@ora>which is the same as:
test@ora>
test@ora> --
test@ora> with t as (
2 select 'true' as f1, 'true' as f2, 'true' as f3, 1 as num from dual union all
3 select 'true', 'true', 'true', 2 from dual union all
4 select 'true', 'false', 'true', 9 from dual union all
5 select 'true', 'false', 'true', 10 from dual union all
6 select 'true', 'true', 'false', 20 from dual union all
7 select 'true', 'true', 'false', 21 from dual)
8 --
9 select f1, f2, sum(num) as total
10 from t
11 group by f1,f2;
F1 F2 TOTAL
true false 19
true true 44
test@ora>
test@ora>with the exception of field3 being SELECTed and shown as NULL.
isotope -
How to use the MAX DATE condition in WHERE CLAUSE FILEDS
Hi,
I am trying to fetch the result for getting maximun date but when i try to execute the query i am getting the error as follows.
CONDITION : trunc(max(RD.DATERECEIVED)) BETWEEN TO_DATE('01/08/2011','DD/MM/YYYY') AND TO_DATE('01/08/2011','DD/MM/YYYY')
ERROR: Group function is not allowed here.
CHEERS,
PRABU AMMAIAPPANI see a couple of problems here.
First, what you posted below is not a syntactically valid query. It seems to be part of a larger query, specifically, this looks to be only the GROUP BY clause of a query.
Prabu ammaiappan wrote:
Hi,
I Have a group function in the Query. Below is the Query i have used it,
GROUP BY S.FREIGHTCLASS,
R.CONTAINERKEY,
S.SKU,
S.DESCR ||S.DESCRIPTION2,
S.PVTYPE,
RD.LOTTABLE06,
R.WAREHOUSEREFERENCE,
RD.TOLOC,
R.ADDWHO,
R.TYPE,
S.CWFLAG,
S.STDNETWGT,
S.ORDERUOM,
R.ADDDATE,
C.DESCRIPTION,
(CASE WHEN P.POKEY LIKE '%PUR%' THEN 'NULL' ELSE to_char(P.PODATE,'dd/mm/yyyy') END),
NVL((CASE WHEN R.ADDWHO='BOOMI' THEN RDD.SUPPLIERNAME END),SS.COMPANY),
RDD.BRAND,
S.NAPA,
RD.RECEIPTKEY,
R.SUSR4,
P.POKEY,
RDD.SUSR1,
r.STATUS, DECODE(RDD.SUSR2,' ',0,'',0,RDD.SUSR2),
rd.SUSR3Second, the answer to your primary question, "How do I add a predicate with with a MAX() function to my where clause?" is that you don't. As you discovered, if you attempt to do so, you'll find it doesn't work. If you stop and think about how SQL is processed, it should make sense to you why the SQL is not valid.
If you want to apply a filter condition such as:
trunc(max(RD.DATERECEIVED)) BETWEEN TO_DATE('01/08/2011','DD/MM/YYYY') AND TO_DATE('01/08/2011','DD/MM/YYYY')you should do it in a HAVING clause, not a where clause:
select ....
from ....
where ....
group by ....
having max(some_date) between this_date and that_date;Hope that helps,
-Mark -
Group by clause will try to group the primay key's
hi all,
For my requiremments and to avoid the the subquery i am using join and group by clause in my sql query in oracle 10g r2 database.my question is if i put a primary column the group clause then oracle try to group the records?.
i know if we use a primary key column in group by clause there is no grouping will occur.
but i have doubt oracle will try to group ? because it will take some amount of time to achive?
else due presense of primay key column in group by clause oracle won't try?
Please advice ??My query return the records less then the min v_date(date datatype) column.
i check this condition in having clause
my old query is
select emp_id,emp_name,voldate,volume,productivity
from volume v1
where v1.voldate<=(select min(v2.voldate) form volume v2 where v2.emp_id=1)
and v1.emp_id=1
i change it as
select emp_id,emp_name,voldate,volume,productivity
from volume v1,volume v2
where v1.emp_id=v2.emp_id
having v1.voldate<=min(v2. voldate)
group by emp_id,emp_name,voldate,volume,productivity
above the query's emp_id is primay key for volume table
comparing both query's which one is the best while looking th response time.
else any other alternative for both the queries.?? -
Problem trying to use a group by clause
hey good day,
i'm trying to use a group by clause in my application, but I'm getting the following error.
Error:- Query cannot be parsed, please check the syntax of your query. (ORA-00979: not a GROUP BY expression)
select "INSTRUCTOR"."EMPNUM",
"INSTRUCTOR"."FIRSTNAME",
"INSTRUCTOR"."LASTNAME",
"QUALN"."SPECIALIZE_FIELD" as "SPECIALIZE_FIELD",
"INSTRUCTOR"."USERNAME"
from "QUALN" "QUALN",
"INSTRUCTOR" "INSTRUCTOR"
where "INSTRUCTOR"."EMPNUM"="QUALN"."EMPNUM"
group by "INSTRUCTOR"."EMPNUM", "INSTRUCTOR"."FIRSTNAME", "INSTRUCTOR"."LASTNAME"Thanks in advance,
RichieRichie wrote:
hey thanks for your reply,
i have tried what you have suggested, but now i got another error
Error :- The report query needs a unique key to identify each row. The supplied key cannot be used for this query. Please edit the report attributes to define a unique key column. ORA-01446: cannot select ROWID from, or sample, a ...
This error message is not from oracle, btu from your reporting tool. it might be MS Access or whatever other tool that you use. Some of these tools want a unique value to identify the current row. The logic applied depends on the relationship of your tables. however in your case you could do it without the group by condition. THen the rowid can still be applied to your query.
Example
note the usage of alias names to simplified the select
select i.EMPNUM ,
i.FIRSTNAME ,
i.LASTNAME ,
i.USERNAME
from INSTRUCTOR i
where i.EMPNUM in (select q.EMPNUM from QUALN q); -
Adding subquery to query w/ Group By clause crashes
Hello all! I am trying to add in the subquery to the statement below. The query works fine before I add in the subquery, but after adding the subquery it will time out. If I comment out the MIN(table1.EOD_DATE) and the Group By clause, the query works fine.
I do not want to do this I need those two items. What am I missing here? Any ideas are appreciated, thanks!
SELECT table1.FUND,
table1.DEPT,
table1.ORG,
table1.ACCT,
LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2) acct_no,
LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT acct_no1,
table2.FUND,
table2.DEPT,
table2.ORG,
table2.ACCT
MIN(table1.EOD_DATE)
FROM table1,
table2
WHERE table1.fund BETWEEN substr(:P_ACCT_FROM,0,3) AND substr(:P_ACCT_TO,0,3)
ANDtable1.dept BETWEEN substr(:P_ACCT_FROM,4,2) AND substr(:P_ACCT_TO,4,2)
ANDtable1.org BETWEEN substr(:P_ACCT_FROM,6,4) AND substr(:P_ACCT_TO,6,4)
ANDtable1.acct BETWEEN substr(:P_ACCT_FROM,10,5) AND substr(:P_ACCT_TO,10,5)
AND floor(table1.acct/10000) in (6,8)
AND SUBSTR(table1.acct,3) != '000'
ANDtable1.eod_date BETWEEN :p_from_date AND :p_to_date
AND table2.fund (+)=table1.fund
AND table2.dept (+)=table1.dept
AND table2.org (+)=table1.org
AND table2.acct (+)=table1.acct
AND table2.type IN( 'PI','JE','PR','VD','VU','AC','AD')
AND table2.po_no IN
SELECT trans.po_no
FROM table2 trans LEFT OUTER JOIN req ON trans.po_no = req.po_no
WHERE (trans.po_no IS NULL OR (TO_CHAR(req.open_date,'YYYY')) = (TO_CHAR(:p_year,'FM9999')))
GROUP BY table1.fund,
table1.dept,
table1.org,
table1.acct,
table2.fund,
table2.dept,
table2.org,
table2.acct
ORDER BY LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2),
LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCTSome untested comments;
AND floor(table1.acct/10000) in (6,8)
AND SUBSTR(table1.acct,3) != '000'Can these two conditions be combined, ie is this the same as;
AND (table1.acct LIKE '0006%' OR table1.acct LIKE '0008%')Ignoring the hard coded dates (assumed they where used for testing) you should avoid using implicit conversions and two digit years;
AND trans.activity_date BETWEEN TO_CHAR('01-jan-2007', 'dd-mon-yyyy') AND TO_CHAR('01-feb-2007', 'dd-mon-yyyy')You can convert your parameters once rather than converting every row by making hte parameter match the column data type;
AND ( trans.po_no IS NULL
OR req.open_date BETWEEN TO_DATE('01-JAN-' || TO_CHAR(:p_year,'9999') || ' 00:00:00' ,'DD-MON-YYYY HH24:MI:SS')
AND TO_DATE('31-DEC-' || TO_CHAR(:p_year,'9999') || ' 23:59:59' ,'DD-MON-YYYY HH24:MI:SS')
) -
Group by clause and having clause in select
hi frnds
plz give me some information of group by and having clause used in select statement with example
thanksThe Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
You can only use the HAVING clause in conjunction with the GROUP BY clause.
To select line groups, use:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
<agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
GROUP BY <s1> <s2> ....
HAVING <cond>.
The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
Example
DATA WA TYPE SFLIGHT.
SELECT CONNID
INTO WA-CONNID
FROM SFLIGHT
WHERE CARRID = 'LH'
GROUP BY CONNID
HAVING SUM( SEATSOCC ) > 300.
WRITE: / WA-CARRID, WA-CONNID.
ENDSELECT.
This example selects groups of lines from database table SFLIGHT with the value LH for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
Specifying Columns Statically
To specify the columns in the GROUP BY clause statically, use:
SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
<agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
GROUP BY <s1> <s 2> ....
To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
Specifying Columns Dynamically
To specify the columns in the GROUP BY clause dynamically, use:
... GROUP BY (<itab>) ...
where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
Example
DATA: CARRID TYPE SFLIGHT-CARRID,
MINIMUM TYPE P DECIMALS 2,
MAXIMUM TYPE P DECIMALS 2.
SELECT CARRID MIN( PRICE ) MAX( PRICE )
INTO (CARRID, MINIMUM, MAXIMUM)
FROM SFLIGHT
GROUP BY CARRID.
WRITE: / CARRID, MINIMUM, MAXIMUM.
ENDSELECT.
regards
vinod -
Why is the GROUP BY clause not working in my Query?
Dear All,
Below is the Query for a Summary Debtors Aged Analysis.
The GROUP BY clause does not seem to be working.
The Query returns all the unpaid invoices, instead of a single total row for each Customer.
If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
This is what GROUP BY is supposed to do, but it is not doing its work.
What has gone wrong?
Thanks
Leon Lai
Here's my Query:
declare @taxdt datetime
set @taxdt
/*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
SELECT
CASE
WHEN T0.Account = 1220101 THEN 'Prim Cust'
WHEN T0.Account = 1220102 THEN 'Fgn Cust'
WHEN T0.Account = 1220103 THEN 'Local Cust'
WHEN T0.Account = 1220104 THEN 'Staff Loan'
WHEN T0.Account = 1220105 THEN 'Dep with TP'
WHEN T0.Account = 1220106 THEN 'Adv to Cust'
WHEN T0.Account = 1220108 THEN 'Sund Drs'
ELSE 'Error ! ! !'
END AS 'Control A/c',
T1.CardCode AS 'BP Code',
T2.Notes2 AS 'BP Name',
SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',
SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',
((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))
AS '1 Mth Ago'
/* Similarly for other age brackets*/
FROM JDT1 T0
INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
LEFT OUTER JOIN OINV T4 ON T3.TransID = T4.TransID
LEFT OUTER JOIN ORIN T5 ON T3.TransID = T5.TransID
WHERE
T1.CardType = 'C'
and (Balance) != 0
and (T0.BalDueDeb - T0.BalDueCred) != 0
GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDateDear Neetu,
Thanks for your reply.
This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
Once I understand the problem, I can adapt your query to suit my requirements
So, let's start with a clean slate:
The Query you have posted is for a DETAILED Debtors Aging Report.
This lists all outstanding invoices, and ages them in the Age Brackets.
What I want is a SUMMARY Debtors Aging Report.
This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
There will be a single row listed for each customer, something like this:
Customer Total Due Current 1 Mth 2 Mth 3 Mth etc
Alfred 500,000 300,000 200,000
Charles 800,000 100,000 300,000 400,000
How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
Thanks
Leon Lai
Here's your code
SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
CASE WHEN T0.TransType=13 THEN 'Invoice'
WHEN T0.TransType=14 THEN 'Credit Note'
WHEN T0.TransType=30 THEN 'Journal'
WHEN T0.TransType=24 THEN 'Receipt'
END AS 'Document Type',
T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
ORDER BY T1.CardCode, T0.DueDate, T0.Ref1 -
How to write a SQL Query without using group by clause
Hi,
Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
Please site an example if is it so,
RegardsI hope this example could illuminate danepc on is problem.
CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
CREATE OR REPLACE FUNCTION GET_ARR return my_array
as
arr my_array;
begin
arr := my_array();
for i in 1..10 loop
arr.extend;
arr(i) := i mod 7;
end loop;
return arr;
end;
select column_value
from table(get_arr)
order by column_value;
select column_value,count(*) occurences
from table(get_arr)
group by column_value
order by column_value;And the output should be something like this:
SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
2 /
Tipo creato.
SQL>
SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
2 as
3 arr my_array;
4 begin
5 arr := my_array();
6 for i in 1..10 loop
7 arr.extend;
8 arr(i) := i mod 7;
9 end loop;
10 return arr;
11 end;
12 /
Funzione creata.
SQL>
SQL>
SQL> select column_value
2 from table(get_arr)
3 order by column_value;
COLUMN_VALUE
0
1
1
2
2
3
3
4
5
6
Selezionate 10 righe.
SQL>
SQL> select column_value,count(*) occurences
2 from table(get_arr)
3 group by column_value
4 order by column_value;
COLUMN_VALUE OCCURENCES
0 1
1 2
2 2
3 2
4 1
5 1
6 1
Selezionate 7 righe.
SQL> Bye Alessandro -
How can I pass multiple condition in where clause with the join table?
Hi:
I need to collect several inputs at run time, and query the record according to the input.
How can I pass multiple conditions in where clause with the join table?
Thanks in advance for any help.
Regards,
TDIf you are using SQL-Plus or Reports you can use lexical parameters like:
SELECT * FROM emp &condition;
When you run the query it will ask for value of condition and you can enter what every you want. Here is a really fun query:
SELECT &columns FROM &tables &condition;
But if you are using Forms. Then you have to change the condition by SET_BLOCK_PROPERTY.
Best of luck! -
How to use order by within Group by clause
Hi All,
I need a help as to how should i use the Order by clause so that the data should be in order with respect to one column, and at the same time whole data is grouped by some other column...like
Select RaceNo,Venue,FP,BP from Race group by RaceNo
Here I want to order by FP in ascending order for each group. When i am using it , whole order is changing.
Can anybody suggest me how to use order by clause that would apply to each group of data.
Thanks .order by clause should be used at the last in any query.......but in group by clause u can't use use that becoz u group according to column then no ordering is needed there......if u want to filter something then u can use having clause and later if u need to arrange then u can use order by clause.........
i hope this eg.l gives u some clarification....
e.g
select deptno,count(empno)
from dept
group by deptno
having count(empno) > 10
order by deptno -
Problem in case of or condition in where clause in case of leftouter joi.
hi
i am encountering a wierd problem.
in a select query if i have a left outer join and a or condition in where clause the order of condition in or matters and if i use a to_char problem is solved.
see query below
select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (CS_FLAG='C' or CS_flag ='B') and custsupp.state = a.id
i have a single record in table custsupp with CS_FLAG ='B' the above does not return result. but if i move CS_FLAG='B' on left of or i.e
select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (CS_FLAG='B' or CS_flag ='C') and custsupp.state = a.id
i get the rsult.
also if i remove left outer join and keep order of condition as it is i get result i.e
select * from custsupp ,state a where (CS_FLAG='C' or CS_flag ='B') and custsupp.state = a.id
also if i add a to_char to co,umns CS_FLAG i get the result.
select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (to_char(CS_FLAG)='C' or to_char(CS_flag ='B')) and custsupp.state = a.id
why it is so?
CS_flag is of type nchar
Shreyas
Edited by: shreyasd on Jun 9, 2010 11:07 PMFirst if you don't want to take credit of the free sample then follow the below procedure:
1. Do the GRN for all the three item and for the free item in the excise tab at the item level select the material as non cenvatable. Just remember to add base value of the item
2. If you want to capture the Part1 entry then just do the normal transaction and while posting the excise with J1IEX just remove the excise duties for the free item.
3. For paying the vendor the excise amount, just do subsequent debit in the MIRO and in the details tab add in the unplanned delivery cost the amount that you want to pay for the excise duties
Second case if you want to take credit of the duties:
1. Do the Normal GRN process, add the base value and excise values for the free item.
2. Post the Excise duites with J1iEX.
3. The with the account entry you can settle the excise payment
Hope this will help you
Enjoyyyyyyyyyyy
Akshit -
Creation of view with clob column in select and group by clause.
Hi,
We are trying to migrate a view from sql server2005 to oracle 10g. It has clob column which is used in group by clause. How can the same be achived in oracle 10g.
Below is the sql statament used in creating view aling with its datatypes.
CREATE OR REPLACE FORCE VIEW "TEST" ("CONTENT_ID", "TITLE", "KEYWORDS", "CONTENT", "ISPOPUP", "CREATED", "SEARCHSTARTDATE", "SEARCHENDDATE", "HITS", "TYPE", "CREATEDBY", "UPDATED", "ISDISPLAYED", "UPDATEDBY", "AVERAGERATING", "VOTES") AS
SELECT content_ec.content_id,
content_ec.title,
content_ec.keywords,
content_ec.content content ,
content_ec.ispopup,
content_ec.created,
content_ec.searchstartdate,
content_ec.searchenddate,
COUNT(contenttracker_ec.contenttracker_id) hits,
contenttypes_ec.type,
users_ec_1.username createdby,
Backup_Latest.created updated,
Backup_Latest.isdisplayed,
users_ec_1.username updatedby,
guideratings.averagerating,
guideratings.votes
FROM users_ec users_ec_1
JOIN Backup_Latest
ON users_ec_1.USER_ID = Backup_Latest.USER_ID
RIGHT JOIN content_ec
JOIN contenttypes_ec
ON content_ec.contenttype_id = contenttypes_ec.contenttype_id
ON Backup_Latest.content_id = content_ec.content_id
LEFT JOIN guideratings
ON content_ec.content_id = guideratings.content_id
LEFT JOIN contenttracker_ec
ON content_ec.content_id = contenttracker_ec.content_id
LEFT JOIN users_ec users_ec_2
ON content_ec.user_id = users_ec_2.USER_ID
GROUP BY content_ec.content_id,
content_ec.title,
content_ec.keywords,
to_char(content_ec.content) ,
content_ec.ispopup,
content_ec.created,
content_ec.searchstartdate,
content_ec.searchenddate,
contenttypes_ec.type,
users_ec_1.username,
Backup_Latest.created,
Backup_Latest.isdisplayed,
users_ec_1.username,
guideratings.averagerating,
guideratings.votes;
Column Name Data TYpe
CONTENT_ID NUMBER(10,0)
TITLE VARCHAR2(50)
KEYWORDS VARCHAR2(100)
CONTENT CLOB
ISPOPUP NUMBER(1,0)
CREATED TIMESTAMP(6)
SEARCHSTARTDATE TIMESTAMP(6)
SEARCHENDDATE TIMESTAMP(6)
HITS NUMBER
TYPE VARCHAR2(50)
CREATEDBY VARCHAR2(20)
UPDATED TIMESTAMP(6)
ISDISPLAYED NUMBER(1,0)
UPDATEDBY VARCHAR2(20)
AVERAGERATING NUMBER
VOTES NUMBERAny help realyy appreciated.
Thanks in advance
Edited by: user512743 on Dec 10, 2008 10:46 PMHello,
Specifically, this should be asked in the
ASP.Net MVC forum on forums.asp.net.
Karl
When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
My Blog: Unlock PowerShell
My Book: Windows PowerShell 2.0 Bible
My E-mail: -join ('6F6C646B61726C40686F746D61696C2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}}) -
-- 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. -
Problem with the query in group by clause
hi, i have problem with group by clause, can some one please help me.
select
header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where
a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id) WHT,
sum(dr),
sum(cr) from temp_tab a
group by header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where
a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id)
select * from temp_tab
drop table temp_tab
create table temp_tab(header_id number ,line_num number, country varchar2(2),
source varchar2(2), dr number, cr number,primary key(header_id,line_num));
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 1,'NL','AP',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 2,'PO','AP',20,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 3,'NL','AP',70,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 1,'NL','PA',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 2,'NL','PA',100,20);
insert into temp_tab(header_id, line_num,country, source, dr,cr) values(3, 1,'KR','PO',100,20);
commit;
Appreciate your help.
Thanks,select header_id,
(select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
where a1.country=a.country
and a1.source='AP'
and a1.header_id=a.header_id) WHT,
sum(dr),
sum(cr)
from temp_tab a
group by header_id
,countryIt's kinda hard to follow what your query does... maybe because I'm only at my second coffee..
Edited by: Alex Nuijten on Oct 2, 2009 8:07 AM
Maybe you are looking for
-
the following sql is not working . If sum(salary) = null should be displayed 1 or 0 select empname,iif((isnull(sum(salary),0)),1,0) from salary group by empname regards Pol polachan
-
As stated above - a blank (UNTITLED) window pops up, but no player, no music. I just had some issues (virus, etc) and my PC was undated, fixed with the newest version of Firefox installed. I'm I now missing something?
-
Is there any way to get the query used in discoverer from backend??
Hi All, I am new to dicoverer. Is there any way to get the query used in discoverer from backend?? Thanks, Sachin
-
Limiting the value of surcharge
Hi all, I have a requirement to limit the value of certain surcharges per line item .(to 75$/ton) material1 (variant) VA00 surcharge1 60$/ton VA00 surcharge2 80$/ton VA00 surcharge3 90$/ton VA00 surcharge1 and VA00 surcharge2 be
-
How to call a write procedures which has output parameters in an xsodata service?
Hi, I have a use case where we call a Stored procedure from an xsodata service, where in I also need some output from procedure. We couldn't achieve this because whenever I pass some output from my procedure , framework is considering the response as