Select COUNT
Hi,
In the same select statement, I want to count based on different criterias. Similar to this
Country Code Country Letters Sent
1 CAN 20 10
2 US 50 13
The count criteria would be different in the "Letters" and "Sent" colunm.
How would I code different COUNT(), in the same select?
Thanks in advance,
Marc.
OK,
Here's my FULL query:
Select * from
-- Number of Letters
(select rpad(i.CD_ITC_ID, 11) ITC_CODE, i.ITC_NAME_EN ITC_NAME,
count(ei.envelope_id) Number_of_letters
from correspondence_request cr, correspondence_event_hist ceh, correspondence_item ci, envelope_item ei, envelope e,
mailing_address m, cd_geographic_division g, cd_itc i
where cr.CD_PROGRAM_GROUP_ID = 4
and ceh.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ceh.EXPIRY_DATE is null
and ci.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ei.CORRESPONDENCE_ITEM_ID = ci.CORRESPONDENCE_ITEM_ID
and ei.SEQUENCE_NUMBER = 1
and e.ENVELOPE_ID = ei.ENVELOPE_ID
and e.MAILING_ADDRESS_ID_RETRN_ADDRS = m.MAILING_ADDRESS_ID
and m.CD_GEOGRAPHIC_DIVISION_ID = g.CD_GEOGRAPHIC_DIVISION_ID
and g.CD_ITC_ID = i.CD_ITC_ID
and i.CD_ITC_ID = 1 -- MONCTON
and trunc(ceh.DATE_CREATED) = trunc(sysdate)-1
--and to_char(ceh.DATE_CREATED, 'DD-MM-YYYY') = ( SELECT TO_CHAR(SYSDATE -1, 'DD-MM-YYYY') FROM dual)
group by i.CD_ITC_ID, i.ITC_NAME_EN ) a,
-- SENT TO
(select --rpad(i.CD_ITC_ID, 11) ITC_CODE, i.ITC_NAME_EN ITC_NAME,
count(e.envelope_id) SENT_TO
--to_char(dss.DATE_CREATED, 'DD-MM-YYYY'), dss.ENVELOPE_ID
from correspondence_request cr, correspondence_event_hist ceh, correspondence_item ci, envelope_item ei, envelope e,
mailing_address m, cd_geographic_division g, cd_itc i, envelope_delivery_status dss
where cr.CD_PROGRAM_GROUP_ID = 4
and ceh.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ceh.EXPIRY_DATE is null
and ci.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ei.CORRESPONDENCE_ITEM_ID = ci.CORRESPONDENCE_ITEM_ID
and ei.SEQUENCE_NUMBER = 1
and e.ENVELOPE_ID = ei.ENVELOPE_ID
and e.MAILING_ADDRESS_ID_RETRN_ADDRS = m.MAILING_ADDRESS_ID
and m.CD_GEOGRAPHIC_DIVISION_ID = g.CD_GEOGRAPHIC_DIVISION_ID
and g.CD_ITC_ID = i.CD_ITC_ID
and i.CD_ITC_ID = 1 -- MONCTON
and e.ENVELOPE_ID = dss.ENVELOPE_ID
and dss.cd_envelope_status_id = 4
and dss.EXPIRY_DATE is null
and trunc(dss.DATE_CREATED) = trunc(sysdate)-1
--and to_char(dss.DATE_CREATED, 'DD-MM-YYYY') = ( SELECT TO_CHAR(SYSDATE -1, 'DD-MM-YYYY') FROM dual)
group by i.CD_ITC_ID, i.ITC_NAME_EN) ,
-- COMPLETED
(select --rpad(i.CD_ITC_ID, 11) ITC_CODE, i.ITC_NAME_EN ITC_NAME,
count(e.envelope_id) COMPLETED
--to_char(dss.DATE_CREATED, 'DD-MM-YYYY'), dss.ENVELOPE_ID
from correspondence_request cr, correspondence_event_hist ceh, correspondence_item ci, envelope_item ei, envelope e,
mailing_address m, cd_geographic_division g, cd_itc i, envelope_delivery_status dss
where cr.CD_PROGRAM_GROUP_ID = 4
and ceh.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ceh.EXPIRY_DATE is null
and ci.CORRESPONDENCE_REQUEST_ID = cr.CORRESPONDENCE_REQUEST_ID
and ei.CORRESPONDENCE_ITEM_ID = ci.CORRESPONDENCE_ITEM_ID
and ei.SEQUENCE_NUMBER = 1
and e.ENVELOPE_ID = ei.ENVELOPE_ID
and e.MAILING_ADDRESS_ID_RETRN_ADDRS = m.MAILING_ADDRESS_ID
and m.CD_GEOGRAPHIC_DIVISION_ID = g.CD_GEOGRAPHIC_DIVISION_ID
and g.CD_ITC_ID = i.CD_ITC_ID
and i.CD_ITC_ID = 1 -- MONCTON
and e.ENVELOPE_ID = dss.ENVELOPE_ID
and dss.cd_envelope_status_id(+) = 3
and dss.EXPIRY_DATE is null
and trunc(dss.DATE_CREATED(+)) = trunc(sysdate)-1
-- and to_char(dss.DATE_CREATED, 'DD-MM-YYYY') = ( SELECT TO_CHAR(SYSDATE -1, 'DD-MM-YYYY') FROM dual)
group by i.CD_ITC_ID, i.ITC_NAME_EN) Even the COMPLETED column returns nothing, I still want the results coming out like this:
ITC CODE NAME NUMBER OF LETTERS SENT TO COMPLETED
1 Mont 23 10 0right now, nothing comes out. Because the COMPLETED part returns no rows.
Please Help,
Marc.
Similar Messages
-
Performance issue when using select count on large tables
Hello Experts,
I have a requirement where i need to get count of data from a database table.Later on i need to display the count in ALV format.
As per my requirement, I have to use this select count inside a nested loops.
Below is the count snippet:
LOOP at systems assigning <fs_sc_systems>.
LOOP at date assigning <fs_sc_date>.
SELECT COUNT( DISTINCT crmd_orderadm_i~header )
FROM crmd_orderadm_i
INNER JOIN bbp_pdigp
ON crmd_orderadm_iclient EQ bbp_pdigpclient "MANDT is referred as client
AND crmd_orderadm_iguid EQ bbp_pdigpguid
INTO w_sc_count
WHERE crmd_orderadm_i~created_at BETWEEN <fs_sc_date>-start_timestamp
AND <fs_sc_date>-end_timestamp
AND bbp_pdigp~zz_scsys EQ <fs_sc_systems>-sys_name.
endloop.
endloop.
In the above code snippet,
<fs_sc_systems>-sys_name is having the system name,
<fs_sc_date>-start_timestamp is having the start date of month
and <fs_sc_date>-end_timestamp is the end date of month.
Also the data in tables crmd_orderadm_i and bbp_pdigp is very large and it increases every day.
Now,the above select query is taking a lot of time to give the count due to which i am facing performance issues.
Can any one pls help me out to optimize this code.
Thanks,
SumanHi Choudhary Suman ,
Try this:
SELECT crmd_orderadm_i~header
INTO it_header " interna table
FROM crmd_orderadm_i
INNER JOIN bbp_pdigp
ON crmd_orderadm_iclient EQ bbp_pdigpclient
AND crmd_orderadm_iguid EQ bbp_pdigpguid
FOR ALL ENTRIES IN date
WHERE crmd_orderadm_i~created_at BETWEEN date-start_timestamp
AND date-end_timestamp
AND bbp_pdigp~zz_scsys EQ date-sys_name.
SORT it_header BY header.
DELETE ADJACENT DUPLICATES FROM it_header
COMPARING header.
describe table it_header lines v_lines.
Hope this information is help to you.
Regards,
José -
"select count(*)" and "select single *" returns different result
Good day!
product version SAP ECC 6.0
oracle10
data transfers from external oracle db into customer tables using direct oracle db link
sometimes I get case with different results from 2 statements
*mytable has 10 rows
*1st statement
data: cnt type I value 0.
select count( * ) into cnt from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
*cnt returns 10 - correct
*2nd statement
select single * from mytable WHERE myfield_0 = 123 and myfield_1 = '123'.
*sy-dbcnt returns 0
*sy-subrc returns 4 - incorrect, 10 rows are "invisible"
but
1. se16 shows correct row number
2. I update just one row from "invisible" rows using se16 and 2nd statement returns correct result after that
can not understand why
thank you in advance.Thank you, Vishal
but,
general problem is that
1. both statements have the same WHERE conditions
2. 1st return resultset with data (sy-dbcnt=10), 2nd return empty dataset, but must return 1 in sy-dbcnt
Yes, different meaning, you are right, but must 2nd must return 1, because of "select single *" construction, not 0.
Dataset to process is the same, WHERE conditions are equal...
I think the problem is that how ABAP interperets select count(*) and "select single *".
Maybe "select count (*)" scans only PK from index page(s)? and "select single *" scans data pages? and something is wrong with that?
I'm new in SAP and didn't find any SAP tool to trace dump of data and indexes pages with Native SQL.
se16 shows all records.
And why after simple manual update of just one record using se16 "select single *" returns 1?
I've just marked one row to update, didn't change any data, then pressed "save". -
Select count from large fact tables with bitmap indexes on them
Hi..
I have several large fact tables with bitmap indexes on them, and when I do a select count from these tables, I get a different result than when I do a select count, column one from the table, group by column one. I don't have any null values in these columns. Is there a patch or a one-off that can rectify this.
ThxYou may have corruption in the index if the queries ...
Select /*+ full(t) */ count(*) from my_table t
... and ...
Select /*+ index_combine(t my_index) */ count(*) from my_table t;
... give different results.
Look at metalink for patches, and in the meantime drop-and-recreate the indexes or make them unusable then rebuild them. -
Select count(*) statement in ABAP
Hi,
Im writing following statement in my Function module,
select count(*) into l_count
from user_master
where username = l_username and
process_type = processtype and
password = oldpassword.
And there is one entry in table user_master.
But still, I'm getting l_count as zero..
Can somebody help me with this.
Regards,
Ameyselect count(*) into l_count
from user_master
where username = l_username and
process_type = processtype and
password = oldpassword.
Use group by option...
Like this....
select count(*) into l_count
from user_master
where username = l_username and
process_type = processtype and
password = oldpassword group by username. -
Select Count(*) from Sample_table - how to get the count using JDBC?
Hi All,
It would be glad if anyone could help me with this. The problem is that I have to get the 'count' of records selected from a arbitrary table say, 'sample_table'. Is that possible to form the SQL in JDBC as
Select Count(*) from Sample_table
and get the value of the count? If yes, how?
Thanks in advance
Prabzstmt = con.createStatement();
ResultSet recordcnt_rs = stmt.executeQuery("Select Count (*) as record_ctr From Sample_table");
recordcnt_rs.next();
record_ctr = recordcnt_rs.getInt("record_ctr");
hope this helps. -
Select count(*) for each row of a table
Hello All,
Following query gives a statistics for each user (how many items he owns, home many tickets authored, how many objects he is subscribed to etc...)
select auser.userid,
(select count(*) from item where owner like '%' || auser.id || '%') ITEM_OWNER_CNT,
(select count(*) from tkt where originator = auser.id) TKT_ORIGINATE_CNT,
(select count(*) from tkt where assigned_to = auser.id) TKT_QA_CNT,
(select count(*) from tkt where create_user = auser.id) TKT_AUTHOR_CNT,
(select count(*) from subscriptions where subscriber_id = auser.id) SUBSCRIPTION_CNT
from
user auser
I was not happy with the performance of this query, so I tried the same using group by. The performance was even worse.
Is there any other option for me to try? Please advice.
Thanks,
SathishHi, Sathish,
As SBH said, a lot depends on your data. Please post some sample data (CREATE TABLE adn INSERT statemetns) for all tables, and the results you want from that data. Describe and give examples of any relationships that are not one-to-one..
You probably want to do joings, like SBH suggested, rather than scalar sub-queries.
The connection between the auser and item tables
(select count(*) from item where owner like '%' || auser.id || '%') ITEM_OWNER_CNT,is very suspicious. Perhaps the item table is poorly designed, and the query would be faster if that table were changed. Is changing the design of the item table an option?
You should be able to get all the information from the tkt table in one pass. It looks like you need to unpivot the data, so instead of one row per ticket (with 3 different people connected to it), there are 3 rows per ticket, each with only 1 person referenced. This is not necessarily a bad table design. Unpivoting, even more than most other things, depends on your database version, so you'll have to tell what version of Oracle you're using. -
Why is the select Count too slow
I am doing the following select count and calling it from my JSP to get the total number of records... why is it so slow...
select count(*)
from
(select distinct o.receive_id, o.name, o.address
from order o, item i
where o.id = i.id
and o.status = 2 and i.status = 0)If the data in the table that you are referring to in the query gets refreshed very often and your high water mark on your table not reset, then this query always runs longer. While deleting data in the table, use 'TRUNCATE' rather than 'DELETE' in your data queries. that would help reset the high water mark and your count() queries will run very very fast.
-
Select count * is not working
Hi everybody.
I've got a very strange problem, when i'm doing a select count* the result is giving me a value that is not the maximum (but when i check the database table the maximum value is another..)
Could it be that the select command is not executing against the table, rather than the SAP cache??
If this is the case, how can i avoid this?? I mean force the select command to execute against de DB table.
thanks a lot.to get max value of a table u can use
Select max( fld )............
Bypassing the SAP buffer with the above additions is a means to increase the performance when accessing buffered database tables. To explicitly bypass the SAP buffer in the SELECT statement, always use the addition BYPASSING BUFFER instead of the implicit behavior of the additions stated above. -
Select count(*) from table in oracle 11g with direct path read takes time
select count(*) from table takes long time, even more than couple of hours..
direct path read is the wait event which is almost is at 99%..
can u someone provide some info on this.. on solution.. thankxknowledgespring wrote:
table has millions of records... 130 millions..
select count(*) from BIG_SIZE_TABLE; --- executed in sql plus command prompt.
Rows Execution Plan
0 SELECT STATEMENT MODE: ALL_ROWS
0 SORT (AGGREGATE)
0 TABLE ACCESS MODE: ANALYZED (FULL) OF 'BIG_SIZE_TABLE' (TABLE)
Elapsed times include waiting on following events:
Event waited on Times Max. Wait Total Waited
---------------------------------------- Waited ---------- ------------
SQL*Net message to client 1 0.00 0.00
enq: KO - fast object checkpoint 1 0.01 0.01
Disk file operations I/O 18 0.00 0.00
direct path read 58921 0.34 418.54direct path read time waited is : 58921 total time waited: 418.54
That 418 seconds - not the hours you reported earlier. Is it possible that your connection to the database broke ?
On a typical system, by the way, you can usually turn one direct read for tablescan into 1MB, so your scan seems to have covered about 59 GB, which seems to be in the right sort of ballpark for 130M rows.
we have another query and when we test the query execution using v$sql, is_bind_sensitive =N, how to make is_bind_sensitive=Y all the time.. There is a hint /*+ bind_aware */ - I'd have to check whether or not it's documented at present. It might help.
I would be interested in hearing why you think the hint should be bind sensitive when the optimizer doesn't.
Regards
Jonathan Lewis -
SELECT COUNT( ) gives warning in ECC6.0.
Hi,
The following query is giving syntax error in ECC6.0, where as it worked absolutely fine in 3.1i server.
SELECT COUNT( OBOX_CNTNO ) FROM ZT2OB
INTO W_COUNT
WHERE SUPPL_CD = W_SUPPL_CD
AND INVC_NO = W_INVC_NO
AND INVC_LN_NO = T_SCR_ITEMS-INVC_LN_NO.
Error: "COUNT( OBOX_CNTNO )" is only valid in the extended form "COUNT( DIS
OBOX_CNTNO )" . . .
The query seems obsolete in ECC6.0. Can anybody help me to give valid query for this in ECC6.0?Hi,
<b>Count</b> functionality is to be used along with <b>Distinct</b> functionality.
COUNT( DISTINCT col )
<b>Reward points if this helps,</b>
Kiran -
Sub-Select Count query breaking TOAD
Oracle 10.2.0.4.0
Running TOAD 9.1
I am running some SQL on our eBusiness Suite:
SELECT pha.segment1
, pha.type_lookup_code
, (SELECT COUNT(DISTINCT pha2.po_header_id)
FROM po.po_headers_all pha2
, po.po_lines_all pla
WHERE pha2.po_header_id = pla.po_header_id
AND pla.contract_id = pha.po_header_id) po_count
, (SELECT MAX(pha2.creation_date)
FROM po.po_headers_all pha2
, po.po_lines_all pla
WHERE pha2.po_header_id = pla.po_header_id
AND pla.contract_id = pha.po_header_id) latest_cpa_po
FROM po.po_headers_all pha
, po.po_vendors pv
, po.po_vendor_sites_all pvsa
WHERE pha.vendor_id = pv.vendor_id
AND pha.vendor_site_id = pvsa.vendor_site_id
-- AND pv.VENDOR_NAME LIKE 'H%'
AND pha.vendor_id = 98
AND pha.type_lookup_code = 'CONTRACT'
AND pha.org_id IN(7041, 7042);The above query runs quicky (approx. 1 second). If I take out the AND pha.vendor_id = 98 then the query takes a few minutes to run.
When I try to export it, or scroll down to view > 500 rows, TOAD crashes.
I know this isn't a TOAD forum, but I think that this is probably an issue with my no doubt rubbish SQL.
If I take out this sub-select, then the problem doesn't happen:
, (SELECT COUNT(DISTINCT pha2.po_header_id)
FROM po.po_headers_all pha2
, po.po_lines_all pla
WHERE pha2.po_header_id = pla.po_header_id
AND pla.contract_id = pha.po_header_id) po_countHowever, I can't work out a better way of getting the data I need.
The sub-select counts POs which have been raised where the contractID on the PO line is the same as the PO Header ID from the main query.
Any advice please, on what I could do to sort this out would be much appreciated.
Thanks!Hi,
It looks like you can replace both scalar sub-queries with a join, like this:
WITH header_lines_summary AS
SELECT pla.contract_id
, COUNT (DISTINCT pha2.po_header_id) AS po_count
, MAX (pha2.creation_date) AS latest_cpa_po
FROM po.po_headers_all pha2
, po.po_lines_all pla
WHERE pha2.po_header_id = pla.po_header_id
GROUP BY pla.contract_id
) -- Everything up to this line is new
SELECT pha.segment1
, pha.type_lookup_code
, hls.po_count -- Changed
, hls.latest_cpa_po -- Changed
FROM po.po_headers_all pha
, po.po_vendors pv
, po.po_vendor_sites_all pvsa
, header_lines_summary hls -- New
WHERE pha.vendor_id = pv.vendor_id
AND pha.vendor_site_id = pvsa.vendor_site_id
AND pha.po_header_id = hls.contract_id (+) -- New
-- AND pv.VENDOR_NAME LIKE 'H%'
AND pha.vendor_id = 98
AND pha.type_lookup_code = 'CONTRACT'
AND pha.org_id IN (7041, 7042);Aside from the sub-query (which is entirely new), the query above is just what you posted, with 2 lines changed and 2 lines added, as marked.
This should be more efficient, but I don't know for certain that it will solve the Toad problem.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
It never hurts to say what version of Oracle you're using. -
Hi,
I have an odd situation where "select count(*) from my_view where some_clause" returns 0, but the exact same query fetching the data (ie "select * from my_view where some_clause") works fine and fetches, correctly, 4000+ records.
I have tried dropping and recreating the view, and collecting DB stats again, but the problem persists.
I had a look at the explain plans and they are very different, but both the SQL statements work fine on a copy of the database taken with impdp.
Does anyone have any suggestions on what might be going on here ?
Any help would be appreciated, I've run out of ideas !
Dave
Edited by: user10281551 on 18-Sep-2008 00:43
Edited by: user10281551 on 18-Sep-2008 00:44Maybe it's the bug that a function based index is present and gets incorrectly used in the select count(*) statement?
If that's not the case, then please show us more details, like the statement and both execution plans.
Regards,
Rob. -
Alternative for select count('x') or count(*)
Hi Gurus,
I need to use select count(*) multiple times in a SP before and after deletion of rows from multiple tables. As this is an expensive method, do we have some alternative for Count(*), like selecting something from a system table or view instead?Hi
You can know the number of rows affected by the DELETE statement in PL/SQL (if you are using PL/SQL) using sql%rowcount. So you don't really need to count the rows again after the delete took place...
If you are deleting the same rows as selected by the second count condition (older than a particular date), in fact you only need to count rows once for each table.
Luis -
Select * shows 1 record - select count(*) shows 2232 records
Using SQL 2008 R2 and SS Import Wizard
Imported Excel file into SQL Table. No errors reported during import.
Command: Select * From XLImport
returns 1 record
Command: Select Count(*) From XLImport
returns 2232
What could be causing this ??
Many thanks
MisterT99I see what happened.
A previous command issued 'Set ROWCOUNT 1'
When I entered 'Set ROWCOUNT 0' That fixed the problem.
Thanks everyone for your comments.
MisterT99
Cool
That now makes sense
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Hi
Need help with getting a count of different sums:
Table: Stay
Columns: Name, Nights
each name can have multiple rows with different number of nights, now I have a select looking like this:
select sum(nights),name from stay
group by name
The result could look something like this:
1 smith
2 miller
1 grant
1 simpson
2 sharp
How do I do to get a count on the sum(night)? Is it possible in the same query?If you want to count how many distinct records appear in your current select statement (i.e. 5 in this case), you can do
SELECT count(*) num_distinct_guests,
total_nights,
name
FROM (
SELECT sum(nights) total_nights,
name
FROM stay
GROUP BY name
)If you want the total number of stays, in addition to the total time stayed, use something like
SELECT sum(nights),
name,
count(nights)
FROM stay
GROUP BY name;Justin
Maybe you are looking for
-
Unknown Error in BI 7.0
Hi Gurus, Please let me know if anyone has faced an 'Unknown error while uploading data from the DB table' message while previewing or loading data from an Oracle Source to BI 7.0 using DB Connect. Thanks in advance, Regards, Neo.
-
Text.html=true : open in new window?
1. How can I make msgA[3] text #C0C0C0? 2. How can I make mgsA[3] open in a new window? var format1:TextFormat = new TextFormat(); format1.bold = true; format1.color = 0x666666; format1.size = 15; this.createTextField("scroll_txt", this.getNextHighes
-
How to remove all the printable apps from an HP Photosmart 7520 touchscree​n at once
In typcial HP fashion, the printer is gummed up with commericals and third party apps I do not want. I see how in the ePrint website to delete the apps one by one - which is taking forever.... Is there a way to remove all the apps from the printer at
-
HT204088 Is there a way I can review my app store orders on the web?
I don't use itunes. I see bills on my credit card statement that I think I didn't make. I want to review orders online without using itunes.
-
Screen darkens after booting in Windows mode
I have an intel mac pro that runs windows xp (sp3) on boot camp. Every time i boot up in windows mode, once I reach the desktop, the screen darkens. Windows xp, to my knowlege, does not have the capacity to adjust screen brightness, as that is normal