Quick way to query in group by clause
Hello
I am having a table T1 where dat_col is to have a primary key and having about 150 million data, I need to extract the number in service each month
create table T1 (date of the dat_col,
Identification number,
"Date_col_pk" PRIMARY KEY CONSTRAINT (date_col ' "));
I need the data as below
JAN-2005 - 20000000
2005 02-12999999
.
.
.
Expects more lines to return
with
As T1
(select date ' 2005-01-01' + dbms_random.value (0,555) date_col, id level)
of the double
connect by level<=>=>
)
Select to_char (trunc (date_col, 'mm'), 'MON-YYYY') mon_year, count (*) count_value
from t1
Rollup Group (trunc (date_col, 'mm'))
order of trunc (date_col, 'mm')
MON_YEAR | COUNT_VALUE |
---|---|
JAN-2005 | 66 |
2005 02 | 57 |
MARCH-2005 | 64 |
APR-2005 | 59 |
MAY-2005 | 48 |
JUNE-2005 | 52 |
JUL-2005 | 52 |
AUG-2005 | 58 |
SEVEN.-2005 | 42 |
OCT-2005 | 53 |
NOV-2005 | 60 |
DEC-2005 | 41 |
JAN-2006 | 48 |
FEB-2006 | 61 |
MARCH-2006 | 53 |
APR-2006 | 62 |
MAY-2006 | 57 |
JUNE-2006 | 52 |
JUL-2006 | 15 |
- | 1000 |
Concerning
Etbin
Tags: Database
Similar Questions
-
By the way where and group by clause Cursor
I'm working on a procedure that generates a where clause clause and needs of a group by clause to return the correct results. I'm moving the two where and group variables in the cursor.
The variables are is filled correctly, but when the cursor is created, variables are not in the cursor.
Here's the code I'm working with. It is part of a package, but does no appeal to other parts of the package.
PROCEDURE createFollowUpTask_Exposure (psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE NULL by default,
psAlarmtyp IN tis.tial.alarmtyp%TYPE by default NULL,
psSubtyp IN tis.tial.subtyp%TYPE by default NULL,
pnDays in NUMBER NULL by default,
psKampkod IN tis.tiin.kampkod%TYPE by default NULL,
psKatnr IN tis.tiin.katnr%TYPE by default NULL,
psUtgava IN tis.tiin.utgava%TYPE by default NULL,
psKatslag IN tis.tikg.katslag%TYPE by default NULL,
psProdsyst IN tis.tikg.prodsyst%TYPE by default NULL,
psUppgtyp IN tis.tiin.uppgtyp%TYPE by default NULL,
psProdkod IN tis.tiin.prodkod%TYPE by default NULL,
psStatus IN tis.tiin.status%TYPE by default NULL
) AS
--
cTIAL tis.tial%ROWTYPE;
vLopnr tis.tial.lopnr%TYPE;
vSqlWhere VARCHAR2 (4000);
vGroupBy VARCHAR2 (1000): = "tiin.kampkod, tiin.abnr, tiko.fordsalj;
cSelectCursor SYS_REFCURSOR;
vSqlSelect VARCHAR2 (4000);
psDays VARCHAR2 (50);
cRec T_TIAL_REC;
nCount number: = 0;
--
CURSOR cSqlSelect (SqlWhere IN VARCHAR2, GroupBy IN VARCHAR2) IS
SELECT tiin.kampkod, tiin.abnr, tiko.fordsalj, MAX (tici.regdat) ALARMDATE
OF tis.tiin
JOIN tis.tiko ON tiin.kampkod = tiko.kampkod AND tiin.abnr = tiko.abnr
JOIN core.tici ON tiin.kampkod = tici.kampkod AND tiin.abnr = tici.abnr AND tici.inplnr = tiin.inplnr
WHERE 1 = 1 | SqlWhere
GroupBy GROUP;
--
BEGIN
-If these parameters are null, trigger the error
IF psUppgkedjetyp IS NULL and psSubtyp IS NULL THEN
raise_application_error (-20001,
"String from the event or events must be assigned");
END IF;
-Fill the TIAL values
IF psUppgkedjetyp IS NOT NULL THEN
cTIAL.Uppgkedjetyp: = psUppgkedjetyp;
END IF;
--
IF psAlarmtyp IS NOT NULL THEN
cTIAL.Alarmtyp: = psAlarmtyp;
END IF;
--
cTIAL.Handklass: = 't';
cTIAL.Blobid: = 0;
--
IF pnDays IS NOT NULL THEN
psDays: = '+' | pnDays;
END IF;
IF psSubtyp IS NOT NULL THEN
cTIAL.Subtyp: = psSubtyp;
END IF;
-Create Where clause for cursor
vSqlWhere: = ";
IF psKampkod IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.kampkod ="' | psKampkod | " ' ;
END IF;
--
IF psKatnr IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.katnr ="' | psKatnr | " ' ;
END IF;
--
IF psUtgava IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.utgava ="' | psUtgava | " ' ;
END IF;
--
IF psKatslag IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tikg.katslag ="' | psKatslag | " ' ;
END IF;
--
IF psProdsyst IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tikg.prodsyst ="' | psProdsyst | " ' ;
END IF;
--
IF psUppgtyp IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.uppgtyp ="' | psUppgtyp | " ' ;
END IF;
--
IF psProdkod IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.prodkod ="' | psProdkod | " ' ;
END IF;
--
IF psStatus IS NOT NULL THEN
vSqlWhere: = vSqlWhere | "AND tiin.status ="' | psStatus | " ' ;
END IF;
-Browse all records in input parameters of the meeting and set values required TIAL.
I'm IN cSqlSelect (vSqlWhere, vGroupBy)
--
LOOP
-EXTRACT cSelectCursor INTO cRec;
cTIAL.Kampkod: = ";
cTIAL.Abnr: = ";
cTIAL.Sign: = ";
cTIAL.Alarmdate: = ";
cTIAL.Kampkod: = i.Kampkod;
cTIAL.Abnr: = i.Abnr;
cTIAL.Sign: = i.fordsalj;
cTIAL.Alarmdate: = i.alarmdate;
--
nCount: = nCount + 1;
--
IF vLopnr = - 1 THEN
raise_application_error (-20002,
"Error creating task for: ' | '. cTIAL.Kampkod |' '|| cTIAL.Abnr |' Sales representative: ' | cTIAL.Alarmdate);
END IF;
END LOOP;
DBMS_OUTPUT. Put_line (' I created ' | nCount |) "documents.");
END createFollowUpTask_Exposure;
Thanks in advance for any help.Hello
Welcome to the forum!
Try this (untested) example:
PROCEDURE createFollowUpTask_Exposure(psUppgkedjetyp IN tis.tial.uppgkedjetyp%TYPE DEFAULT NULL, psAlarmtyp IN tis.tial.alarmtyp%TYPE DEFAULT NULL, psSubtyp IN tis.tial.subtyp%TYPE DEFAULT NULL, pnDays IN NUMBER DEFAULT NULL, psKampkod IN tis.tiin.kampkod%TYPE DEFAULT NULL, psKatnr IN tis.tiin.katnr%TYPE DEFAULT NULL, psUtgava IN tis.tiin.utgava%TYPE DEFAULT NULL, psKatslag IN tis.tikg.katslag%TYPE DEFAULT NULL, psProdsyst IN tis.tikg.prodsyst%TYPE DEFAULT NULL, psUppgtyp IN tis.tiin.uppgtyp%TYPE DEFAULT NULL, psProdkod IN tis.tiin.prodkod%TYPE DEFAULT NULL, psStatus IN tis.tiin.status%TYPE DEFAULT NULL) AS -- cTIAL tis.tial%ROWTYPE; vLopnr tis.tial.lopnr%TYPE; vSqlWhere VARCHAR2(4000); vGroupBy VARCHAR2(1000) := ' tiin.kampkod, tiin.abnr, tiko.fordsalj'; cSelectCursor SYS_REFCURSOR; vSqlSelect VARCHAR2(4000); psDays VARCHAR2(50); cRec T_TIAL_REC; nCount NUMBER := 0; FUNCTION fnc_cSqlSelect(SqlWhere IN VARCHAR2, GroupBy IN VARCHAR2) RETURN VARCHAR2 IS BEGIN RETURN 'SELECT tiin.kampkod, tiin.abnr, tiko.fordsalj, MAX(tici.regdat) ALARMDATE FROM tis.tiin JOIN tis.tiko ON tiin.kampkod = tiko.kampkod AND tiin.abnr = tiko.abnr JOIN core.tici ON tiin.kampkod = tici.kampkod AND tiin.abnr = tici.abnr AND tici.inplnr = tiin.inplnr WHERE 1 = 1 ' || SqlWhere || ' GROUP BY ' || GroupBy; END fnc_cSqlSelect; BEGIN -- If these parameters are null, raise error IF psUppgkedjetyp IS NULL AND psSubtyp IS NULL THEN raise_application_error(-20001, 'Either Event Chain or Starting Event must be assigned'); END IF; -- Populate TIAL values IF psUppgkedjetyp IS NOT NULL THEN cTIAL.Uppgkedjetyp := psUppgkedjetyp; END IF; -- IF psAlarmtyp IS NOT NULL THEN cTIAL.Alarmtyp := psAlarmtyp; END IF; -- cTIAL.Handklass := 'T'; cTIAL.Blobid := 0; -- IF pnDays IS NOT NULL THEN psDays := '+ ' || pnDays; END IF; IF psSubtyp IS NOT NULL THEN cTIAL.Subtyp := psSubtyp; END IF; -- Create Where clause for cursor vSqlWhere := ''; IF psKampkod IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.kampkod = ''' || psKampkod || ''''; END IF; -- IF psKatnr IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.katnr = ''' || psKatnr || ''''; END IF; -- IF psUtgava IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.utgava = ''' || psUtgava || ''''; END IF; -- IF psKatslag IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tikg.katslag = ''' || psKatslag || ''''; END IF; -- IF psProdsyst IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tikg.prodsyst = ''' || psProdsyst || ''''; END IF; -- IF psUppgtyp IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.uppgtyp = ''' || psUppgtyp || ''''; END IF; -- IF psProdkod IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.prodkod = ''' || psProdkod || ''''; END IF; -- IF psStatus IS NOT NULL THEN vSqlWhere := vSqlWhere || ' AND tiin.status = ''' || psStatus || ''''; END IF;ç -- Loop through all records meeting input parameters and set required TIAL values. OPEN cSelectCursor FOR fnc_cSqlSelect(vSqlWhere, vGroupBy); LOOP FETCH cSelectCursor INTO v; -- You must define a variable 'v' to hold the data of cursor EXIT WHEN cSelectCursor%NOTFOUND; --FETCH cSelectCursor INTO cRec; cTIAL.Kampkod := ''; cTIAL.Abnr := ''; cTIAL.Sign := ''; cTIAL.Alarmdate := ''; cTIAL.Kampkod := i.Kampkod; cTIAL.Abnr := i.Abnr; cTIAL.Sign := i.fordsalj; cTIAL.Alarmdate := i.alarmdate; -- nCount := nCount + 1; -- IF vLopnr = -1 THEN raise_application_error(-20002, 'Error Creating task for: ' || cTIAL.Kampkod || ' ' || cTIAL.Abnr || ' Sales Rep: ' || cTIAL.Alarmdate); END IF; END LOOP; CLOSE cSelectCursor; DBMS_OUTPUT.PUT_LINE('I created ' || nCount || ' records.'); END createFollowUpTask_Exposure; /
Kind regards
-
Can not find a way to bypass the Group
The following query runs as is, but only because I have included IntervForcl, IsSpecial , in the group by clause. I don't want group by these things, that month. I have no idea how to write this query, do what I want, I tried everything. Any suggestion would be appreciated.
The end result is supossed to look something like this:
PostedDate RushMargin NonRushMargin InteriorMargin
2013.01 65.4% 42% 21.5%
2013.02 62.7% 43.5% 32%
2013.03 67.3% 41.1% 29.8%
SELECT CONVERT (varchar (7), APPostedWhen, 102) AS [PostedDate].
[InteriorMargin] = BOX
WHEN intervforcl = 'k' THEN CAST (((APAMOUNT) AVG / AVG (ARAMOUNT)) * 100 AS DECIMAL (12,2))
END,
[RushMargin] = BOX
WHEN IsSpecial = '1' CAST (((APAMOUNT) AVG / AVG (ARAMOUNT)) * 100 AS DECIMAL (12,2))
END,
[NonRushMargin] = BOX
WHEN IsSpecial <>'1' THEN CAST (((APAMOUNT) AVG / AVG (ARAMOUNT)) * 100 AS DECIMAL (12,2))
END
Inspections
WHERE DATEDIFF (MONTH, APPostedWhen, SYSDATETIME ()) < 6 AND ARAMOUNT > 0 AND APAMOUNT > 0
GROUP OF CONVERT (varchar (7), APPostedWhen, 102)IntervForcl, IsSpecial
ORDER BY [PostedDate]
It is a forum for oracle pl/sql.
What you think you have TSQL.
However we need conditions case inside aggregate functions, I guess.
as
CAST ((AVG (affaire quand intervforcl = 'k' alors fin APAMOUNT) / AVG (case...)) (ARAMOUNT)) * 100 AS DECIMAL (12,2))
and so on.
Be careful on the way in which the aggregate function deal with NULL values.
-
Select the columns not in the group by clause
Hello
My version of DB is 10.0.2
I have query, where in I need to select two columns more but that should not be part of the group by Clause.
Does perform a work around?
SELECT F.custnum, V.Import_date, -- F.ErledigtMM,F.ErledigtGrundMM, (Columns to be selected additionally) nvl(sum(nvl(round(V.VerAuf16/1000,2), 0) +nvl(round(V.VerAuf17/1000,2), 0) + nvl(round(V.VerAuf18/1000,2), 0) + nvl(round(V.VerAuf19/1000,2), 0) + nvl(round(V.VerAuf20/1000,2), 0) + nvl(round(V.VerAufKAPUn/1000,2), 0) + nvl(round(V.VerAufKAPVz/1000,2), 0) ), 0) Mandantenforderung, nvl(sum(nvl(round(V.VerAuf4/1000,2), 0) ), 0) Inkassokosten, nvl(sum(nvl(round(V.VerAuf5/1000,2), 0) ), 0) KontoFuehrungsgebuehren, nvl(sum(nvl(round(V.VerAuf1/1000,2), 0) + nvl(round(V.VerAuf2/1000,2), 0) ), 0) Verwertungskosten, nvl(sum(nvl(round(V.VerAuf10/1000,2), 0) + nvl(round(V.VerAuf8/1000,2), 0) + nvl(round(V.VerAuf9/1000,2), 0) ), 0) Barauslagen, nvl(sum(nvl(round(V.VerAuf13/1000,2), 0) + nvl(round(V.VerAuf14/1000,2), 0) + nvl(round(V.VerAuf15/1000,2), 0) + nvl(round(V.VerAuf6/1000,2), 0) ),0) Gerichtskosten, nvl(sum(nvl(round(V.VerAuf11/1000,2), 0) + nvl(round(V.VerAuf12/1000,2), 0) + nvl(round(V.VerAuf7/1000,2), 0) ), 0) RAKosten, TO_CHAR(F.Created_Date,'MM.YYYY') Created_Date_MM , TO_CHAR(F.Created_Date,'YYYY') Created_Date_MMRRRR FROM FACM F, VA V WHERE F.custnum = DECODE(0,0,F.custnum,0) AND F.accnum = V.accnum GROUP BY F.custnum, V.Import_date,TO_CHAR(F.Created_Date,'MM.YYYY') ,TO_CHAR(F.Created_Date,'YYYY'))
Hello
Here's what I suggest:
select a.custnum, a.import_date, b.ErledigtMM, b.ErledigtGrundMM, a.Mandantenforderung, a.Inkassokosten, a.KontoFuehrungsgebuehren, a.Verwertungskosten, a.Barauslagen, a.Gerichtskosten, a.RAKosten, a.Created_Date_MM , a.Created_Date_MMRRRR from ( SELECT F.custnum, V.Import_date, nvl(sum(nvl(round(V.VerAuf16/1000,2), 0) +nvl(round(V.VerAuf17/1000,2), 0) + nvl(round(V.VerAuf18/1000,2), 0) + nvl(round(V.VerAuf19/1000,2), 0) + nvl(round(V.VerAuf20/1000,2), 0) + nvl(round(V.VerAufKAPUn/1000,2), 0) + nvl(round(V.VerAufKAPVz/1000,2), 0) ), 0) Mandantenforderung, nvl(sum(nvl(round(V.VerAuf4/1000,2), 0) ), 0) Inkassokosten, nvl(sum(nvl(round(V.VerAuf5/1000,2), 0) ), 0) KontoFuehrungsgebuehren, nvl(sum(nvl(round(V.VerAuf1/1000,2), 0) + nvl(round(V.VerAuf2/1000,2), 0) ), 0) Verwertungskosten, nvl(sum(nvl(round(V.VerAuf10/1000,2), 0) + nvl(round(V.VerAuf8/1000,2), 0) + nvl(round(V.VerAuf9/1000,2), 0) ), 0) Barauslagen, nvl(sum(nvl(round(V.VerAuf13/1000,2), 0) + nvl(round(V.VerAuf14/1000,2), 0) + nvl(round(V.VerAuf15/1000,2), 0) + nvl(round(V.VerAuf6/1000,2), 0) ),0) Gerichtskosten, nvl(sum(nvl(round(V.VerAuf11/1000,2), 0) + nvl(round(V.VerAuf12/1000,2), 0) + nvl(round(V.VerAuf7/1000,2), 0) ), 0) RAKosten, TO_CHAR(F.Created_Date,'MM.YYYY') Created_Date_MM , TO_CHAR(F.Created_Date,'YYYY') Created_Date_MMRRRR FROM FACM F, VA V WHERE F.custnum = DECODE(0,0,F.custnum,0) AND F.accnum = V.accnum GROUP BY F.custnum, V.Import_date,TO_CHAR(F.Created_Date,'MM.YYYY') ,TO_CHAR(F.Created_Date,'YYYY')) ) a, FACM b where b.custnum = a.custnum
By the way
WHERE F.custnum = DECODE(0,0,F.custnum,0) AND F.accnum = V.accnum
can be translated into
WHERE F.accnum = V.accnum
because
F.custnum = DECODE(0,0,F.custnum,0)
is always true
becauseDECODE(0,0,F.custnum,0)
means
if 0=0 then F.custnum else 0
-
How to include stmt cases in a group by clause
Hi I have a question,
How can I include a case statement in the group by clause?
For example:
Select
(case when x.ctry is null then y.ctry to another x.ctry end) as chief operating officer.
sum (x.in_amt)
Of
tbl1 x,
TBL2 y
where
x.ID = y.id
Group
(case when x.ctry is null then y.ctry to another x.ctry end)
Assume, I had millions of records in the tables, then my guess is, the above query could take huge time.
Any other way to do it?CD / wrote:
To delete the expression in the GROUP BY clause. I'm advocating no improvement in performance, I don't have?No, you didn't. And your advice can remove in fact the expression in the GROUP BY clause. But I am still confused as to why this would be an end in itself.
Kind regards
Rob. -
Is there a simple and quick way of deleting these temporary files?
To clear my comp. congestion and help speed up my PC, my ISP told me to put temp5 Prefetch and % and Temp in start-run to delete the temporary files. It's a bit long-winded that each group must be deleted separately. Disk Clean up does not get rid of them. Is there a simple and quick way of deleting these temporary files? Thanks Brian
To clear my comp. congestion and help speed up my PC, my ISP told me to put temp5 Prefetch and % and Temp in start-run to delete the temporary files. It's a bit long-winded that each group must be deleted separately. Disk Clean up does not get rid of them. Is there a simple and quick way of deleting these temporary files? Thanks Brian
Delete the contents of the prefetch folder will not help speed things up. In fact, it will probably slow things down. See http://answers.microsoft.com/en-us/windows/forum/windows_vista-system/can-i-delete-the-data-in-the-prefetch-folder/c54a8e56-c8cf-451d-a88f-07f06a2f2d54
I guess temp5% is a typo and you really wanted to say %Temp%. Percent signs indicate that it is an "environment variable" with the usual value of C:\Documents and Settings\, yourusername\Local Settings\TempThe directory specified by %Temp% is, in fact, the directory cleaned by the cleaning of record under the name "temporary files". Why do you think that disk cleanup is not delete files? Note that disk cleanup does not remove the files in this directory which came in the last 7 days (this period may be changed by changing a registry value).
What disk cleanup does NOT, however, is to clean temporary files, files for the Internet browser cache and other files in places of profile-specific to the user of different profiles that you are currently using. Disk Cleanup also does not delete the contents of C:\Windows\Temp (although it doesn't fill up with very much). C:\Windows\Temp is the directory that appears when you type Temp in start > run (without the percent sign). And, of course, disk cleanup will not empty the cache of the browser by non-Microsoft browsers, e.g. Firefox.
There are third-party applications that make a "deep" cleaning Some of them clean files of all users without having to login to each profile separately. Most understand the characteristics that you should not use.
Here are 2 - there are others, but I haven't used.
ATF-Cleaner (do not delete prefetch)
CCleaner (do not use the registry tool)You might be interested in "How to automate the disk cleanup tool in Windows XP"
-
Need of a query with all the clauses
Hi all
I have been asked for a query to write using clauses in sql as a group by, where, having, order by in a single query. I just write the query below but I have no out put. Please do not correct where I'm missing.
Select deptno, max (sal) in the group by deptno emp having deptno > (select distinct deptno from emp where deptno > = 20)
Thank you for your time and information.
Removed the ' > ' your subquery that is causing the "ORA-01427: einreihig subquery returns more than one line.
SELECT deptno,
Max (SAL)
WCP
GROUP BY deptno
HAVING deptno >
(SEPARATE FROM SELECT Deptno emp WHERE deptno = 20
);
Another example
--------------------------
SELECT deptno,
Sum (SAL)
WCP
-WHERE deptno = 20
Deptno group
HAVING SUM (sal) > 9000
ORDER BY deptno;
-
-SQL - GROUP BY clause: fields of nonaggregate mandate
Hello
I study data (especially data recovery) and found something interesting.
When you use an aggregate function in the SELECT clause, it is mandatory to have all fields that are not aggregated in the SELECT clause to be there in the GROUP BY clause.
For example,.
SELECT dept_no, Salary
The EMPLOYEE
GROUP BY dept_no;
The SQL above works fine.
But what happens if the user forgets the dept_no in the GROUP BY clause or the clause GROUP BY itself is missing?
Certainly, it is a mistake.
Why this error is not handled by the database. I mean, the database must be smart/pretty smart to add the GROUP BY clause by itself. So let's assume that, if I miss the GROUP BY clause or miss a field no aggregated from the SELECT clause when I get at least an aggregate function on a field with at least a no aggregated field in the SELECT clause, the database should check the GROUP BY clause at compile time and add mandate missed the fields in the GROUP BY clause.
Example,
SQL1:_
SELECT dept_no, Salary
The EMPLOYEE
GROUP BY dept_no;
SQL2:_
SELECT dept_no, Salary
The EMPLOYEE;
Here, the SQL1 and SQL2, both should give me same output without error.
I can't understand why this is handled?Hello
998478 wrote:
... If we mix the aggregated and non-aggregated values, then there must be a GROUP BY clause that contains all non-aggregated values. Why this is handled by the database/compiler itself?It IS managed by the compiler itself. The compiler manages to trigger an error. The compiler has no way of knowing if you want to remove something from the SELECT clause, or add something to the GROUP BY clause, or not to use the aggregate functions or use several aggregate functions, or a combination of the above. If the compiler re-writes your code and none of these things done automatically, it would be wrong more often that he was right, and you would (rightly) complain about his behavior.
For example, it is clearly wrong:
SELECT deptno , job , SUM (sal) FROM scott.emp GROUP BY deptno ;
What is the right way to fix it?
1. remove something from the SELECT clause
SELECT deptno , SUM (sal) FROM scott.emp GROUP BY deptno ;
2. add something to the GROUP BY clause
SELECT deptno , job , SUM (sal) FROM scott.emp GROUP BY deptno , job ;
3. do not use aggregate functions
SELECT deptno , job , sal FROM scott.emp ;
4. use several aggregate functions
SELECT deptno , MIN (job) , SUM (sal) FROM scott.emp GROUP BY deptno ;
What are all the options, either. For example, the correct solution would be to use analytical functions instead of aggregate functions.
How can anyone tell which of them is right? They all have the right answer for some problem.Moreover, by saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit oversimplified.
Fuller, here's the ABC of GROUP BY:
When you use a GROUP BY clause or in an aggregate function, then all in the SELECT clause must be:
(A) a ggregate function,
(B) one of the expressions "group By."
(C) adding to C, or
(D) something that Depends on the foregoing. (For example, if you "GROUP BY TRUNC (dt)", you can SELECT "TO_CHAR (TRUNC (dt), 'Mon - DD')").Published by: Frank Kulash on April 13, 2013 13:44
Additional code examples. -
Quick way to replace fill stroke?
I have a number of objects filled with different colors.
Is there a quick way to swap their hunger and colors of race all at once in the same way that can be made with unique colors with Shift + X?
rcraighead wrote:
Or W_J_T thank you. It'll be very useful.
Ha ha. You're welcome, have fun. (But as much respect @ CarlosCanto, I learned so much from his positions among others)
Larry G. Schneider wrote:
The selection must be separated to make it work.
Update: Version 2 - it includes groups and compounds.
// // Version: v2 -- added Groups and Compounds, in regards to Larry G. Schneider's comment // Script Purpose: Swap Fill and Stroke Colors // Script Name: Swap_Fills_and_Strokes_W_J_T_v2.js // Author: W_J_T , 2/6/2014 // Reference Thread: http://forums.adobe.com/message/6091991 // function swapColorFillsStrokes() { if (app.documents.length == 0) { alert("ERROR:\nNo Open / Active Document Found"); } else { var doc = app.activeDocument; var sel = doc.selection; if (sel == 0) { alert("ERROR:\nPlease select one or more items in order to\nswap their fill and stroke colors."); } else { var i, j, k, jl, kl, curItem for (i = 0, l = sel.length; i < l; i++) { var curItem = sel[i] if (curItem.typename == "CompoundPathItem") { for (j = 0, jl = curItem.pathItems.length; j < jl; j++) { swapColor(curItem.pathItems[j]) } } else if (curItem.typename == "GroupItem") { for (k = 0, kl = curItem.pathItems.length; k < kl; k++) { swapColor(curItem.pathItems[k]) } } else if (curItem.typename == "PathItem") { swapColor(curItem); } } function swapColor(obj) { var fColor = obj.fillColor; var sColor = obj.strokeColor; obj.fillColor = sColor; obj.strokeColor = fColor; } } } } swapColorFillsStrokes();
-
Reg - search form for a VO in group by clause
Hello
I have a bar chart that displays data based on the query below.
SELECT THE STATE. BATCH AS STATUSID, STATUS. STATUS, COUNTY (SR. SERVICEREQUEST_ID) AS SRCOUNT
OF SR, SERVICEREQUESTSTATUS STATE SERVICE_REQUEST
WHERE SR. BATCH = STATUS. BATCH
GROUP STATUS. BATCH, STATUS. STATUS, SR. BATCH
It displays the number of SRs against a particular status.
Now, I need to add a search form to this graph with the customer and the date range.
So you need to add the following line to the place where clause.
SR. "CUSTOMER_ID =: customerId AND SR. "BETWEEN REQUESTED_ON: fromDate and: to this day.
But the SR columns. CUSTOMER_ID, SR. REQUESTED_ON also needs to be added to the select clause to create criteria for the search panel view.
The two columns should also be added to the group by clause if you want to add in the select clause.
This would not produce the expected results.
How to create a search with the criteria only form in the where clause. Help, please.
With respect,
Guna[Url http://docs.oracle.com/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/server/ViewObjectImpl.html] ViewObjectImpl has methods to do this programmatically (setQuery, defineNamedWhereClauseParam, setNamedWhereClauseParam) that you can use to manipulate the query variables bind expected and the values of the lie.
John
-
ORA-00907: lack the right parenthesis when using Group by clause with xmlagg
I have the following query and I am getting ORA-00907 error when I use the clause with the xmlagg function group.
If I remove the clause xmlagg and the group by clause, the query works well and not give me the result.select xmlelement("Mitigation", xmlelement("m_szMethodName",tm.DisplayName), xmlelement("SubstanceInterferenceProtocolList", (select xmlagg(xmlelement("MitigationProtocol", xmlelement("m_szMethodName",tm.DisplayName), xmlelement("m_szInterferenceProtocolName",tmp.protocol_name), xmlelement("m_szInterferenceSubstance",tmp.intf_mtrl_prod_code), xmlelement("m_ProtocolParameters", xmlelement("m_szProtocolName",tmp.protocol_name), xmlelement("m_Consumables", xmlelement("Consumable", xmlelement("m_szConsumId", xrl.rgnt_pack_name), xmlelement("m_szProductCode",xrl.pack_prod_code), xmlelement("m_nVolume",tmp.fluid_vol), xmlelement("m_szProtocolStep",xps.protocol_step_name))), xmlelement("m_ProtParamList", xmlagg( xmlelement("ParameterValues", xmlelement("m_szProtocolName",tmp.protocol_name), xmlelement("m_Time",xpsd.parameter_ntime_value)) group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code) ))) order by tmp.ccd_test_id, tmp.intf_mtrl_prod_code, xps.protocol_step_intprotocolstep ) from XPR_tdef_mitigation_protocol tmp, xp_reagentlist xrl, xpr_protocol_settings xps, xpr_protocol_settings_default xpsd where tmp.ccd_test_id = tm.ccd_test_id and tmp.ccd_test_id = xrl.ccd_test_id and tmp.pack_prod_code = xrl.pack_prod_code and tmp.intf_type = 1 and xps.protocol_name = xpsd.protocol_name and xps.protocol_step_name = xpsd.protocol_step_name and xps.ps_action_parameterlist = xpsd.ps_action_parameterlist and xps.protocol_name = tmp.PROTOCOL_NAME ))) from XPtoXPRTdef_defn_mapping tm where tm.DisplayName = 'SYPH'
But in this code XML, the output format is incorrect for my application.
Could someone help out here?Now my problem is that this unique coating is more than 32767 characters and utl_file can write 32767 bytes per line.
Someone deal with this?Serialize the output as CLOB and DBMS_XSLPROCESSOR.clob2file procedure used to write to a file:
DECLARE xml_output CLOB; BEGIN SELECT XMLElement("Department", XMLAgg( XMLElement("Employee",e.job_id||' '||e.last_name) ORDER BY e.last_name ) ).getClobVal() AS "Dept_list" INTO xml_output FROM hr.employees e WHERE e.department_id = 30 OR e.department_id = 40; DBMS_XSLPROCESSOR.clob2file(xml_output, 'XML_DIR', 'test.xml'); END; /
-
can do without group by clause report through parameter
Hello expert,
I need to create a report in which the user select a field and adds this field in the group by clause of the sql query.
I know that the notion of setting lexical but getting only not the idea how the user for the group by clause...
I tried the following
Select trunc (m.spc_doc_date),
-d.spc_item_code,
Sum (NVL(d.req_qty,0)) x, sum (nvl(d.spc_item_qty,0)) y
of spc_ppc_daily_m m, spc_ppc_daily_d d
where m.spc_doc_ # in (select spc_doc_ # from spc_ppc_daily_m where fncl_year = 20112012)
and m.fncl_year = 20112012
and d.blce_qty > 0
and m.spc_locn_code = 400001
"and m.spc_doc_date between February 1, 2012'-February 29, 2012"
and m.spc_locn_code = d.spc_locn_code
and m.fncl_year = d.fncl_year
and m.spc_doc_ #= d.spc_doc_ #.
Group by & g_by
----------------------------
g_by is the report parameter
Thank you
Yoannyash_08031983 wrote:
Hello HamidBut when I compile my sql triggers Error statement due to & g_by or: g_by parameter.
Hello, yoann
Most likely, you are getting error ORA-00936 .
If the error above is true, then you are missing a part in sql.
First without lexical parameter your query should be ok. Correct your query without lexical parameter, and then add the lexical parameter.
Try thisselect trunc(m.spc_doc_date), --d.spc_item_code, sum(nvl(d.req_qty,0)) x,sum(nvl(d.spc_item_qty,0)) y from spc_ppc_daily_m m, spc_ppc_daily_d d where m.spc_doc_# in(select spc_doc_# from spc_ppc_daily_m where fncl_year=20112012) and m.fncl_year=20112012 and d.blce_qty>0 and m.spc_locn_code=400001 and m.spc_doc_date between '01-feb-2012' and '29-feb-2012' and m.spc_locn_code=d.spc_locn_code and m.fncl_year=d.fncl_year and m.spc_doc_#=d.spc_doc_# group by trunc(m.spc_doc_date) &g_by
Hope this helps...
-
Hi all
Can someone tell me what is wrong with the query below? I get an exception is NOT a GROUP OF CLAUSE:
SELECT LAST_DAY((xxx.timevalue)) as SUMMARYDATE , xxx.acct AS ACCTNUM , xxx.referenceid AS SEARCHTYPE , CASE WHEN NVL(xxx.PRIMARYSRCH_IND,'N') = 'Y' THEN COUNT(xxx.searchid) ELSE 0 END Cnt_PrimarySearches , CASE WHEN NVL(xxx.primarysrch_ind,'N') = 'N' THEN COUNT(xxx.Searchid) ELSE 0 END Cnt_SecondarySearches FROM XXX_Tablename xxx WHERE xxx.referenceid NOT IN ('Alert','Search','Collection') GROUP BY LAST_DAY((xxx.timevalue)) , xxx.acctnum , xxx.referenceid
Hello
Try this
SELECT LAST_DAY((xxx.timevalue)) as SUMMARYDATE , xxx.acct AS ACCTNUM , xxx.referenceid AS SEARCHTYPE ,COUNT( CASE WHEN NVL(xxx.PRIMARYSRCH_IND,'N') = 'Y' THEN (xxx.searchid) ELSE 0 END Cnt_PrimarySearches) , COUNT(CASE WHEN NVL(xxx.primarysrch_ind,'N') = 'N' THEN (xxx.Searchid) ELSE 0 END) Cnt_SecondarySearches FROM XXX_Tablename xxx WHERE xxx.referenceid NOT IN ('Alert','Search','Collection') GROUP BY LAST_DAY((xxx.timevalue)) , xxx.acctnum , xxx.referenceid
Not tested
-
Understanding of the multiple GROUP BY clause column
Hi all
Suppose I have the HR schema example, what is the difference between these two codes?
andselect department_id, job_id, count(*) from employees GROUP BY department_id, job_id ORDER BY 1,2;
I do not see the difference when I run these queries.select department_id, job_id, count(*) from employees GROUP BY job_id,department_id ORDER BY 1,2;
Best regards
ValerieWell, semantically there is no difference: the two queries are equivalent, they return the same result as the value of lines.
The order of columns in a GROUP BY clause is unrelated to the result set of a query. You group by this "group of columns.
And since you order two games using the exact same ORDER BY clause, the order in which Oracle returns the bag of lines is the same too in your case.
-
Need help with query outputing group names
I'm trying to find a way for groups of output headers, then all the records in each group etc header. It would be easy, except there is a key with what I want to do.
Normally, if I have this data set (that I've ' borrowed' a site that showed the closest to what I was looking for):
Example table:
TABLE [number]
(Name, NUMBER)
Dave Bower 843-444-4444
Dave Bower 843-555-5555
Matthew Small 843-111-1111
Matthew Small _843-222-2222
Matthew Small 843-333-3333
I could use the following code:
< cfoutput query = "somequery" group = "name" >
#name # < br >
< cfoutput >
#phonenumber # < br >
< / cfoutput >
< hr >
< / cfoutput >
And get this:
Dave Bower
843-444-4444.
843-555-5555.
-------------------
Matthew Small
843-111-1111.
843-222-2222.
843-333-3333.
-------------------
BUT my actual tables are not set up like that. Rather than recording of every name of every record, I would have an ID that is the foreign key to another table.
Current table set up is as follows:
TABLE [people]
(ID, NAME)
1 Dave Bower
2 small Matthew
TABLE [Phones]
(PEOPLE_ID NUMBER)
1 843-444-4444
1 843-555-5555
2 843-111-1111
2 843-222-2222
2 843-333-3333
If this output actually would this give me with my current setup and request above code:
1
843-444-4444.
843-555-5555.
-------------------
2
843-111-1111.
843-222-2222.
843-333-3333.
-------------------
How can I keep my current setup but create a query that produces the same result from the top? (The table names of people like the group headers, but data from the phones table under that output)
You must gather the two tables, and then group the output.
Something along the lines of the (may vary slightly depending on your DB and the exact table structure)
SELECT ppl.name, ph.number
PEOPLE ppl
INNER JOIN phones ph ON ppl.id = ph.people_id
ORDER BY ppl.name
See you soon
Kai
Maybe you are looking for
-
Re: Satellite A65-S1067 - display driver does not work
As stated in my title, the display (ATI Radeon 7000 IGP) on my Toshiba laptop driver does not work and has not worked for quite a while. Whenever I try to play a game that is to install a game (like World of Warcraft or Civilization III) it does not
-
Send the component behind the other
Hello, I am currently playing on the sample application BestCamera community, and I was wondering if I could have a component showing in front of the camera. Currently, I am unable to do this, and I find myself with just the willingness to display ca
-
Server error: 0 x 80048820
Server error: 0 x 80048820 Server: 'https://mail.services.live.com/DeltaSync_v2.0.0/Sync.aspx '. Windows Live Mail error ID: 0 x 80048820
-
Missing folder then drag and drop on the OBIEE catalog view
Hi guys.I had a folder on shared folders and I moved it to a different folder on shared too, using a simple drag and drop on the catalog on OBIEE view and everything by moving my browser crashed.When I logged on again, my folder disappeared. He disap
-
Please help me. I uninstalled all lightroom related and reinstalled and nothing works!