Max count by group query
Hello
Can anyone help with a max count query?
I'm trying to display houses that have had the most viewings by house type.
I need to do a count on viewing date, then display the max count value per group (type_description).
This is what I have so far:
select property.property_id, count(viewing.viewing_date), property_type.type_description
from property, viewing, property_type
where property.property_id = viewing.property_id
and (property.prop_type_id = property_type.prop_type_id)
However, I am not sure how to say I want to display the max count by type_description.
regards
Jo
actually, I'm afraid I don't follow the linked thread at all. I think it's perhaps because I haven't created any views. It's clearly the same assignment, but it looks like an incredibly complicated approach. I am obviously a bit dimmer than my course-mate!
is there another, simpler way of finding the max count and then grouping by type?
Similar Messages
-
Count(*) with group by max(date)
SQL> select xdesc,xcust,xdate from coba1 order by xdesc,xcust,xdate;
XDESC XCUST XDATE
RUB-A 11026 01-JAN-06
RUB-A 11026 05-JAN-06
RUB-A 11026 08-JAN-06
RUB-A 11027 10-JAN-06
RUB-B 11026 02-JAN-06
RUB-B 11026 08-JAN-06
RUB-B 11026 09-JAN-06
RUB-C 11027 08-JAN-06
I want to make sql that result :
XDESC COUNT(*)
RUB-A 2
RUB-B 1
RUB-C 1
Criteria : GROUPING: XDESC XCUST AND MAX(DATE)
bellow mark *** that was selected in count.
XDESC XCUST XDATE
RUB-A 11026 01-JAN-06
RUB-A 11026 05-JAN-06
RUB-A 11026 08-JAN-06 ***
RUB-A 11027 10-JAN-06 ***
---------------------------------------------------------COUNT RUB-A = 2
RUB-B 11026 02-JAN-06
RUB-B 11026 08-JAN-06
RUB-B 11026 09-JAN-06 ***
---------------------------------------------------------COUNT RUB-B = 1
RUB-C 11027 08-JAN-06 ***
--------------------------------------------------------COUNT RUB-C = 1
Can Anybody help ?
I tried :
select xdesc,max(xdate),count(max(xdate)) from coba1 group by xdesc
ERROR at line 1:
ORA-00937: not a single-group group function
ThankThis one is duplicate. see the following link
Count(*) with group by max(date)
Thanks -
Max(count(*))
countries(country_name, country_id, region_id)
Employees(employee_id,first_name, last_name, email, phone_number, hire_date, job_id, salary, commission_PCT, manager_id, department_id)
departments(department_id, location_id, manager_id, department_name)
job_history(employee_id, start_date, end_date, job_id, department_id)
jobs(job_id, job_title, min_salary, max_salary)
locations(location_id, street_address, postal_code, city, state_province, country_id)
regions(region_id, region_name)
question is display all countries that are located in the region which has most countries in the countries table
select country_name
from countries
where region_id=1
--(select max(count(*)) from countries group by region_id)Instead of using 1 where where clause, i need to write a sub query to get the region 1.Oficially tested ;) :
SQL> insert into countries values('France',1,1);
1 row created.
SQL> insert into countries values('Italy',2,1);
1 row created.
SQL> insert into countries values('China',3,2);
1 row created.
SQL> insert into countries values('India',4,2);
1 row created.
SQL> insert into countries values('Mongolia',5,2);
1 row created.
SQL> select country_name,
2 country_id,
3 region_id
4 from countries
5 where (region_id,1) in (
6 select region_id,
7 dense_rank() over(order by count(*) desc) rnk
8 from countries
9 group by region_id
10 )
11 /
COUNTRY_NAME COUNTRY_ID REGION_ID
China 3 2
India 4 2
Mongolia 5 2
SQL> SY. -
I am having trouble with a query.
Table 1
id status
1 STARTED
2 STARTED
3 STARTED
4 STARTED
5 STARTED
6 INCOMPLETE
7 INPROGRESS
Table 2
id individual
1 MMJ
1 JBJ
2 MKJ
3 MKJ
3 LJJ
4 MMJ
5 MMJ
5 JBJ
6 ADJ
7 ADJ
The two tables are linked by id.
The user wants to see the count of STARTED projects for two groups.
Group 1 is MMJ, JBJ, ADJ
Group 2 is MKJ, LJJ
These groups aren’t assigned anywhere in the schema – I just got a list of names and what group they should go into…
How do I go about grouping the individuals and then how do I perform the count?
I did do a count and group by individual but my results are skewed because I get a double count on the ids that have multiple individuals assigned. Can anyone provide some insight?
Thank You!SELECT
SUM(group1),
SUM(group2)
FROM
SELECT DISTINCT
t1.id,
DECODE(t2.individual, 'MMJ', 1, 'JBJ', 1, 'ADJ', 1, 0) group1,
DECODE(t2.individual, 'MKJ', 1, 'LJJ', 1, 0) group2
FROM
(select 1 id, 'STARTED' status from DUAL
union
select 2 id, 'STARTED' status from DUAL
union
select 3 id, 'STARTED' status from DUAL
union
select 4 id, 'STARTED' status from DUAL
union
select 5 id, 'STARTED' status from DUAL
union
select 6 id, 'INCOMPLETE' status from DUAL
union
select 7 id, 'INPROGRESS' status from DUAL
) t1,
(select 1 id, 'MMJ' individual from dual
union
select 1 id, 'JBJ' individual from dual
union
select 2 id, 'MKJ' individual from dual
union
select 3 id, 'MKJ' individual from dual
union
select 3 id, 'LJJ' individual from dual
union
select 4 id, 'MMJ' individual from dual
union
select 5 id, 'MMJ' individual from dual
union
select 5 id, 'JBJ' individual from dual
union
select 6 id, 'ADJ' individual from dual
union
select 7 id, 'ADJ' individual from dual
) t2
WHERE
t1.id = t2.id AND
t1.status = 'STARTED'
SUM(GROUP1) SUM(GROUP2)
3 2 -
Selecting on a Max Count of rows
I would like some advice on the following SQL. I am trying to select the max(count(*)) of a selct count(*). (if you know what I mean??)
select district_id
from (
-- retrieve a list of districts, plus the count of employee related records
select d.district_id, count(*) CountX
from station s, division d
where s.resp_empl_num = :empID and
s.stn_status_code = 'AC' and
s.resp_div_num = d.division_code
group by d.district_id
-- match on the district with the max count #
where CountX = (
select max(count(*))
from station st, division dv
where st.resp_empl_num = :empID and
st.stn_status_code = 'AC' and
st.resp_div_num = dv.division_code
group by dv.district_id
)Try this
select district_id
from ( select district_id,
rank() over (order by count(*) desc) rn
from station s, division d
where s.resp_empl_num = :empID and
s.stn_status_code = 'AC' and
s.resp_div_num = d.division_code
group by d.district_id
) where rn=1
; -
Count(*) with nested query
Hi,
I have a question about the count(*) with nested query.
I have a table T1 with these columns:
C1 number
C2 number
C3 number
C4 number
C5 number
(The type of each column is not relevant for the example.)
This query:
select C1, C2, C3, C4
from T1
group by C1, C2
it's not correct becausa C3 and C4 are not columns specified in the GROUP BY expression.
If if run this query:
select count(*)
from (select C1, C2, C3, C4
from T1
group by C1, C2)
I haven't an error message (the result is correctly the number of records).
Why?
Thanks.
Best regards,
LucaBecause you are just selecting count(*) and none of the columns from the subquery, Oracle is optimising it by ignoring the selected columns and just running the sub query with the group by columns. I know it seems odd, but if you take a basic example:
SQL> ed
Wrote file afiedt.buf
1 select count(*)
2 from (select empno, sal, mgr, deptno
3 from emp
4* group by deptno)
SQL> /
COUNT(*)
3... all columns but deptno are ignored
... but if you include one of the other columns, even if you group by that column...
SQL> ed
Wrote file afiedt.buf
1 select count(*), empno
2 from (select empno, sal, mgr, deptno
3 from emp
4 group by deptno)
5* group by empno
SQL> /
group by empno
ERROR at line 5:
ORA-00979: not a GROUP BY expression
SQL>... the error returns, because you're forcing oracle to include the column in the subquery. -
BAM Data Control - Group query with Active Data Service
Trying to get a group query from a BAM data control to work with Active Data Service in an ADF application (JDeveloper 11.1.1.4.0).
With a flat query, as the data changes, I can see DataChangeEvents fired, resulting in a data push to the client -
<BAMDataChangeEventFilter> <log>
#### DataChangeEvent #### on [DataControl name=CEP_Person_DOB_Flat, binding=data.view_mainPageDef.FlatDOB1.view_pageDefs_FlatDOBViewPageDef_WEB_INF_FlatDOB_xml_FlatDOB.QueryIterator]
Filter/Collection Id : 1966
Collection Level : 0
Event Id : 5
==== DataChangeEntry (#1)
ChangeType : INSERT_AFTER
KeyPath : [2157, 0]
InsertKeyPath : [null, 0]
AttributeNames : [id, _PersonKey, _County, _Surname, _AGE, _DOB, _Country, _FirstName]
AttributeValues : [2157, 10008/129, Vagzukarbsm, Gnnfzxxyqfgpsijcr, 110, Thu Dec 26 00:00:00 GMT 1901, Ekcqvrkoksr, Vwhm]
When I try a group query on the same data, currently just trying to group by _DOB for every 10 years to count the number of people, I get no data change events fired, so don't get any data pushed to the client, though the data has been changed if I refresh the page.
Any ideas ?can you include bam and jdev versions and also include exception from logs?
-
Get max min per group in sequence
I have a list like this below with desired result, please help.
The X are GPS cordinates, the time is the GPS times
X time
A 5
B 6
B 7
C 8
C 9
A 10
B 11
The result must be:
X min max
A 5 5
B 6 7
C 8 9
A 10 10
B 11 11Here is a slightly diff solution, but you need SS 2012 or greater.
The idea is expressed in each CTE.
- Identify each new gps coordinate in time sequence per each car (new_gps).
- Count how many new_gps you have for each row in specific partition and windows frame (grp_helper).
- Aggregate to find min / max for each group (car, x, grp_helper).
- Bring next minTime
- APPLY to split the rows waiting and then moving
SET NOCOUNT ON;
USE tempdb;
GO
Create table #test (Car int, X Char(1), [Time] int)
INSERT INTO #test
VALUES
( 11, 'A', 5 ),
( 11, 'B', 6 ),
( 11, 'B', 7 ),
( 11, 'B', 8 ),
( 11, 'C', 9 ),
( 11, 'C', 10 ),
( 11, 'C', 11 ),
( 11, 'A', 12 ),
( 11, 'B', 13 );
-- ( 12, 'A', 15 ),
-- ( 12, 'B', 16 ),
-- ( 12, 'B', 17 ),
-- ( 12, 'B', 18 );
WITH C1 AS (
SELECT
Car,
X,
[Time],
CASE
WHEN X = LAG(X, 1, NULL) OVER(PARTITION BY Car ORDER BY [Time]) THEN 0 ELSE 1
END AS new_gps
FROM
#test
, C2 AS (
SELECT
Car,
X,
[Time],
SUM(new_gps) OVER(
PARTITION BY Car
ORDER BY [Time]
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS grp_helper
FROM
C1
Agg AS (
SELECT
Car,
X,
MIN([Time]) AS minTime,
MAX([Time]) AS maxTime,
COUNT(*) AS cnt
FROM
C2
GROUP BY
Car,
X,
grp_helper
, C3 AS (
SELECT
Car,
X,
minTime,
maxTime,
cnt,
LEAD(minTime, 1, maxTime) OVER(PARTITION BY Car ORDER BY minTime) AS nxt_minTime
FROM
Agg
SELECT
T.Car,
T.X,
T.minTime,
T.maxTime,
T.moving
FROM
C3
CROSS APPLY
SELECT C3.Car, C3.X, C3.minTime, C3.maxTime, 1 AS moving
WHERE cnt = 1
UNION ALL
SELECT C3.Car, C3.X, C3.minTime, C3.maxTime, 0 AS moving
WHERE cnt > 1
UNION ALL
SELECT C3.Car, C3.X, C3.maxTime, C3.nxt_minTime, 1 AS moving
WHERE cnt > 1
) AS T
ORDER BY
T.Car,
T.minTime;
GO
DROP TABLE #test;
GO
AMB
Some guidelines for posting questions...
AYÚDANOS A AYUDARTE, guía básica de consejos para formular preguntas -
How to get min,max,avg time for query execution?
Dear Friends,
In AWR we are getting avg time taken to execute particular query, how can one get min,max time taken by query during number of executions.
ThanksI would run the sql in a cursor for loop, to get a quite reasonable execution time without changing the actual execution plan:
SQL> show user;
USER is "HR"
SQL> set timing on
SQL> select count(*) from all_objects;
COUNT(*)
55565
Elapsed: 00:00:03.91
SQL> var p_sql varchar2(200)
SQL> exec :p_sql := 'select * from all_objects'
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:03.53
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.75
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.73
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.66
SQL> ---- alter system flush shared_pool;
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.80
SQL> declare
2 t1 timestamp := systimestamp;
3 begin
4 execute immediate 'begin for c in (' || :p_sql || ') loop null; end loop; end;';
5 dbms_output.put_line('Elapsed: ' || (systimestamp - t1));
6 end;
7 /
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.64
SQL>
https://forums.oracle.com/thread/705536?start=15&tstart=0
Regards
Girish Sharma -
What is the max. count of internal worker-threads in B1iSN 88?
Hi Experts,
We have an installation of B1iSN 88 with an ECC 6.0 and 54 SAP Business One installation. The Hardware is 8 Core multi-threads processor. 32GB Memory. Now we have a problem with the queuing of Events. What we have found is that the configuration of the internal worker-threads is set to -1(please see below for the settings). We change the settings to xcl.threads=20 and it improves the queuing. My question is what is the max. count of internal worker-threads per core? so that we can know how many worker will set and if we need to upgrade the CPU to 16 Core..
# The max. count of internal worker-threads afforded for the internal Scheduler (defaults to 1)
# The value of 0 means that there is no limit (what in general should not be set up).
# A negative value means the count of threads per available processor
xcl.threads=-1
Regards,
WilsonYou're very welcome.
Yes, they are very nice machines.
What a jump in performance when I swapped out the Pentium 4 620 mine had, for the PD 945, and tossed in 4 GB of memory.
That box will also run the Radeon HD 6570 with no problem too, which is what I put in mine.
The downside of that model is that there are no settings for ahci or raid.
I own or have owned every CMT since the d510 with the exception of the dc7900.
My main PC is now the 8200 Elite CMT which I installed W8.1 on.
It has an i7-2600 processor and 32 GB of memory, 1 TB SATA III hard drive.
I threw in a Radeon HD 6670 in that one.
Best Regards,
Paul -
Returning a count from a query using Union
Hi. I'm attempting to select a count from this query and then display the total in a message, but I'm getting a 'Too many rows returned' (ORA-01422). Can anyone tell me how I can achieve a total for this query?
SELECT nvl(count(*),0)
INTO conflict_cnt
FROM dropper_assign
WHERE dropper_id = :dropper_vacations.dropper_id AND
trunc(sched_date) between :begin_dt and :end_dt
union
SELECT nvl(count(*),0)
FROM exfc.bundle a, splits b
WHERE a.bundle = b.bundle AND
b.dropper_id = :dropper_vacations.dropper_id AND
trunc(a.actual_dt) between :begin_dt and :end_dt;
call_alert.the_error('test: '||to_char(conflict_cnt));Any help would be greatly appreciated.Thanks Christian, I can know return to my favourite present occupation named HOLIDAYS ;)
btw with count function as the first message
WITH
data AS
SELECT
COUNT(*) cnt
FROM
dual
CONNECT BY level <= 10
UNION
SELECT
COUNT(*) cnt
FROM
dual
CONNECT BY level <= 20
SELECT
SUM(cnt)
FROM
data
SUM(CNT)
30
/* and */
WITH
data AS
SELECT
COUNT(*) cnt
FROM
dual
CONNECT BY level <= 10
UNION ALL /****** returns me also 30 *****/
SELECT
COUNT(*) cnt
FROM
dual
CONNECT BY level <= 20
SELECT
SUM(cnt)
FROM
data
SUM(CNT)
30 result will defer only if both count return exactly the same value so definitely UNION ALL for that case or the simple solution I have provided before ...
but leave it. that's enough messages for this thread ;)
Jean-Yves
Edited by: JeanYves Bernier on 9 août 2011 17:42 -
How can I evaluate the count of a query I'd like to execute with a map...
Hi. I have a problem with a query...
I hava created a query which a execute with a Map (I use the
executeWithMap(Map) method). The problem is that sometimes this query
returns a large resultset. So, I would like to execute an other query
(called query_count) before executing ther final query with the Map. If
the query_count returns a count < 200, I execute the final query. How can
I do ? There is an example I have read this in the documentation :
Query query = pm.newQuery (Magazine.class, "price < 5");
query.setResult ("count(this)");
Long count = (Long) query.execute ();
The problem in this example is that the query is not execute with a Map.
So my question is : "How can we do the evalute the count of a query we
would like to execute with a map ?". Thank you for any response.Hi John,
You should be able to executeWithMap that query, too. Is that giving you
problems?
Note that there may be an easier solution. What do you do if there are more
than 200 results? If, e.g., you just get the first N, then one option is to
set the FetchBatchSize on the query to N (thus activating large result set
support), and then call size () on the resulting Collection. This will
issue a SELECT COUNT(*) to the database to determine the size automatically.
Thanks,
Greg
"John" <[email protected]> wrote in message
news:ctq9a8$4gr$[email protected]..
>
Hi. I have a problem with a query...
I hava created a query which a execute with a Map (I use the
executeWithMap(Map) method). The problem is that sometimes this query
returns a large resultset. So, I would like to execute an other query
(called query_count) before executing ther final query with the Map. If
the query_count returns a count < 200, I execute the final query. How can
I do ? There is an example I have read this in the documentation :
Query query = pm.newQuery (Magazine.class, "price < 5");
query.setResult ("count(this)");
Long count = (Long) query.execute ();
The problem in this example is that the query is not execute with a Map.
So my question is : "How can we do the evalute the count of a query we
would like to execute with a map ?". Thank you for any response. -
How to create Infoset&user group query--(query report)
Hi Guys,
how to create Infoset&user group query--(query report),
Pls send me the exact procedure with Example....
Regards:
Kumar .Ggoto SQ03 and create an User Group If U want to create Ur Own.
Goto SQ02 to create Ur Infoset by Giving Logical database name or Simple Database table
Then Choose What ever data U need to be included in The Qurey in field Groups.
Then Generate the Infoset
Now Assign the infoset to user group
Now goto SQ01 and Click on Other user group Button and choose Ur user Group.
Then in the USer group select Ur Infoset and then create Ur own Query and save this.
Now select the infoset query and goto More functions under Query menu and Generate report name.
Now Create a transaction code for the report name generated.
Now use the Tcode.
Hope U have got the basic idea of creating Queries.
~BiSu -
How to get count of group of current login user if AD Group is added in SharePoint Group?
My Client has 2 SharePoint Application. For the AD Users they have created AD Group and added users in that AD Group as per requirement. Later AD Group is added in SharePoint Group. When I'm trying to fetch Current User Group count, I can able to get the
count of Groups using below statement.
int groupCount = SPContext.Current.Web.CurrentUser.Groups.Count;
Above Statement, returns always 0 value if I tried with User who are added in AD Group and if I add AD User and then it will return the exact count.
Please suggest solution to get Count of Group of Current User. My Application contains more than 60 SharePoint group.Hello,
I believe your code doesn't count those AD group users until they login at least once. If this is the case then try to use "SPUtility.GetPrincipalsInGroup" as suggested in below post:
http://stackoverflow.com/questions/4314767/getting-members-of-an-ad-domain-group-using-sharepoint-api
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help -
how can ı find column count of dynamic query
is there a simple way
thanksYou can use DBMS_SQL to facilitate this:
CREATE OR REPLACE FUNCTION count_sql( p_sql IN CLOB )
RETURN INTEGER
AS
lv_cursor_id INTEGER;
lv_columns DBMS_SQL.DESC_TAB;
lv_column_count INTEGER;
BEGIN
-- Open Cursor
lv_cursor_id := DBMS_SQL.OPEN_CURSOR;
-- Parse Cursor
DBMS_SQL.PARSE
( c => lv_cursor_id
, statement => p_sql
, language_flag => DBMS_SQL.NATIVE
-- Describe Columns
DBMS_SQL.DESCRIBE_COLUMNS
( c => lv_cursor_id
, col_cnt => lv_column_count
, desc_t => lv_columns
-- Close Cursor
DBMS_SQL.CLOSE_CURSOR(lv_cursor_id);
RETURN lv_column_count;
END count_sql;
/Example:
SQL > SELECT * FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE 11.2.0.1.0 Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL > SELECT count_sql('SELECT dummy, dummy, CASE WHEN dummy = ''X'' THEN 1 ELSE 0 END AS col FROM DUAL') FROM DUAL;
COUNT_SQL('SELECTDUMMY,DUMMY,CASEWHENDUMMY=''X''THEN1ELSE0ENDASCOLFROMDUAL')
3
SQL > SELECT count_sql('SELECT dummy, dummy, dummy, ''Y'' FROM DUAL') FROM DUAL;
COUNT_SQL('SELECTDUMMY,DUMMY,DUMMY,''Y''FROMDUAL')
4Hope this helps!
Maybe you are looking for
-
Outlook notes...howto sync them to my Blackberry z 10
I keep a lot of information in Outlook notes...used to sync them to my Blackberry, I recently activated my new Z10 with the blackberry balance and notices that i lost all my notes. is there a way to fix this?
-
How to read StarOffice Spreadsheet using Oracle Form?
Hi all I want to read StarOffice spreadsheet with few columns in Oracle forms. I have done this with Microsoft Excel but not with StarOffice. Does anyone have idea regards how to do this? Rgds
-
Hi , My scnearo was working fine . Suddenly i am getting this error in moni error while refreshing cache if any one ever faced this problem plz let me now thanks amit
-
White noise in video problem - Adobe premiere pro 4
Sometimes i face this issue when making projects with Adobe Premiere Pro 4. Original movie file played with VLC player looks good - like "converted" (just converted using external program, codec H.264/Mpeg4) in Premiere. But original movie from camer
-
EAR deploy in a not homogeneus Cluster
Hi, we a shared NFS Directory between the Cluster members and we like to deploy on some members only the Web Apps (Presentation) and on the others only the Ejbs (Application Layer). The Ear is currently unjared in a Directory, as the Web Ap