Counting records (2 tables envolved)
Good Day,
I need to count all the records in a table (NGIN_VAS_LOGS) where one of its column (ANUM) LIKES or having a prefix equal to a column (ACCESS_CODE) in another table (REF_NGIN_VAS_AC_CP).
Here's my query
>> SELECT ACCESS_CODE, COUNT(*) AS CNT FROM (
>> SELECT ANUM , ACCESS_CODE
>> FROM NGIN_VAS_LOGS , REF_NGIN_VAS_AC_CP WHERE
>> ANUM LIKE ACCESS_CODE||'%'
>> ) GROUP BY ACCESS_CODE ORDER BY CNT DESC;
The query's result is correct , however it execution time took very long
Here's the Tables:
NGIN_VAS_LOGS
ANUM
NAME
63908
Fred
63907
Love
63906
Tina
63805
Klayton
REF_NGIN_VAS_AC_CP
ACCESS_CODE
DESCRIPTION
639
School
638
Business
Result :
ACCESS_CODE
CNT
639
3
638
1
Please do let me know ,if there is any other best way to achieve this. Thank you and Godbless
Hi,
I think your structure is not correct. Please tell us what will happen if in 2 second table you will below records
638
Business
639
School
6394
School New
And in main table you have
63908
Fred
63907
Love
63906
Tina
63805
Klayton
63948
Test
Please tell us how many records must return for 639 and for 6394 ????
Did you understand what i would like to notice???
Ramin Hashimzade
Similar Messages
-
How to count records in table and send email only if count 0
I thought this would be fairly simple, but apparently not. I'm trying to count the number of records I have in my staging table, and send an email if count > 0 . . . . and . . . . I want to put the count in the body of the email.
I'm running into a problem with the concatenation part of it.
SET NOCOUNT ON
SELECT * FROM [dbo].[Staging]
SELECT @@rowcount as Row_Count
SET NOCOUNT OFF
IF @@rowcount > 0
BEGIN
exec msdb.dbo.sp_send_dbmail @profile_name = 'MailTest',
@recipients = '[email protected]',
@subject = 'Successfully Loaded Production',
@body = 'Successfully Loaded Production ' + @@rowcount + ' records loaded',
@body_format = 'text'
END
The problem comes from the '+' character not being recognized. Maybe it's out of scope, not sure.
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.Try this
SET NOCOUNT ON
IF EXISTS (SELECT TOP 1 1 FROM [dbo].[Staging])
BEGIN
exec msdb.dbo.sp_send_dbmail @profile_name = 'MailTest',
@recipients = '[email protected]',
@subject = 'Successfully Loaded Production',
@body = 'Successfully Loaded Production ' + @@rowcount + ' records loaded',
@body_format = 'text'
END
Thanks
Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers -
Count Records in Table Except If Related Record Exists in Child Table
Dear All
I have the following query that counts all of the records in the table SENAlert based upon the teacher's username in a related table.
SELECT COUNT(SENAlert.SENAlertID) AS Expr1
FROM Class INNER JOIN ClassMember ON Class.ClassClassCode = ClassMember.ClassMemberClassCode
INNER JOIN Student ON ClassMember.ClassMemberStudentID = Student.StudentID
INNER JOIN SENAlert ON Student.StudentID = SENAlert.SENAlertStudentID
INNER JOIN Teacher ON Class.ClassTeacherCode = Teacher.TeacherCode
WHERE (Teacher.TeacherUsername = 'dsmith')
I need to extend this query by adding another table called SENAlertHistory. I would like to count the number of alerts (SENAlertID) for the specified teacher
but where there is no related record in the SENAlertHistory table. Here's what the relationship diagram looks like:
What's going to happen is when a teacher clicks a button to say they have read an alert, I will record this in the SENAlertHistory table. Therefore when performing a count of how many unread alerts the teacher has, I need to ignore the alerts they have
already read (i.e. the records in the SENAlertHistory table).
This is a bit too advanced for me -- I have tried! I was hoping someone would be able to help me please?
Many thanks
DanielTry below code
-- If you dont need the read alert count
SELECT COUNT(SENAlert.SENAlertID) AS Expr1
FROM Class INNER JOIN ClassMember ON Class.ClassClassCode = ClassMember.ClassMemberClassCode
INNER JOIN Student ON ClassMember.ClassMemberStudentID = Student.StudentID
INNER JOIN SENAlert ON Student.StudentID = SENAlert.SENAlertStudentID
INNER JOIN Teacher ON Class.ClassTeacherCode = Teacher.TeacherCode
WHERE (Teacher.TeacherUsername = 'dsmith')
AND NOT EXISTS
(SELECT * FROM SenAlertHistory SAH WHERE Teacher.TeacherCode = SAH.SenAlertHistoryTeacherCode and SENAlert.SENAlertID = SAH.SEMAlertHistorySENAlertID )
-- If you need the read alert count
SELECT COUNT(SENAlert.SENAlertID) - COUNT(SAH.SEMAlertHistorySENAlertID) AS Expr1,COUNT(SAH.SEMAlertHistorySENAlertID)readalert
FROM Class INNER JOIN ClassMember ON Class.ClassClassCode = ClassMember.ClassMemberClassCode
INNER JOIN Student ON ClassMember.ClassMemberStudentID = Student.StudentID
INNER JOIN SENAlert ON Student.StudentID = SENAlert.SENAlertStudentID
INNER JOIN Teacher ON Class.ClassTeacherCode = Teacher.TeacherCode
LEFT OUTER JOIN SenAlertHistory SAH ON Teacher.TeacherCode = SAH.SenAlertHistoryTeacherCode and SENAlert.SENAlertID = SAH.SEMAlertHistorySENAlertID
WHERE (Teacher.TeacherUsername = 'dsmith')
Thanks
Saravana Kumar C -
Hi,
I want to check total records in each table in my schema. How is this possible.
tks
satyaMy answer is correct and it is expected behaviour:
F.e:
SQL> select count(*) from SYS._default_auditing_options_;
select count(*) from SYS._default_auditing_options_
ERROR at line 1:
ORA-00911: invalid characterThe same is in my code as I am selecting from DBA_TABLES (Yes, you asked from your schema).
Edited by: drop.any on Nov 7, 2009 12:35 AM -
Count records in table where fields not used in Report
Hi
I was wondering if anyone could help me with a problem I have. I am new to Crystal Reports... I am using CR2008 and XSD as a datasource.
I have the following tables used in the report.
Programme Table Risk Table Control Table Test Table
ID ID ID ID
Name ProgrammeID RiskID ControlID
Details Description Description Description
Opinion Notes Notes Notes
Risk Recs Table Control Recs Table Test Rec Table
ID ID ID
RiskID ControlID TestID
Description Description Description
In the report that I have to design, I need to display the Notes from each of the Risk, Control and Test tables in hierarchical order and also display the notes when there are one or more recommendations attached to each Notes.
Risk Notes - Display only when risk rec count <> 0
Control Notes - Display only when control rec count <> 0
Test Notes - Display only when test rec count <> 0
So far I have designed the report as follows:
I have grouping around the Risk Notes, Control Notes and Test Notes as
Group 1 - Group by ProgrammeID
Group 2 - Group by RiskID
Group 3 - Group by ControlID
Group 4 - Group by TestID
(This is giving me the notes in the order that I want)
Since I want to know if each of the risk, control and test have got any recommendations, I created summary counts to get the recommendation count for Risk, Control and Tests. But I am not able to get the right count. Effectively, what I need to do is go through the Risk Recommendation table and count the recommendations that belong to that particular RiskID. If the count = 0 then I want to supress the Risk Notes (Group Header 2.)
Can anyone suggest how to get the count?
ThanksHi
I am using Distinct Count.
When there are no recommendations then the count always comes out as 1 and the count is correct for the first grouping. After that even if there are more than one recommendation, the count is always 1!
How do I reset a summary count?
I even tried writing a formula to do the count..
NumberVar riskCount;
WhilePrintingRecords;
riskCount := DistinctCount ({RiskRec.ID}, {Control.RiskID})
and another formula to reset this count, even then the count is still coming out incorrect. It brings a value 1 when there are no recommendations and the count is right for one set of grouping only.
I have just recently started using CR and havent quite mastered it yet!
Thanks... -
How I will get recordcount for all the tables with table name in my user
with a single query??
I have only select privilege . So I am not abel to create any schema, insert statement in my user.
Message was edited by:
Sumit SauTABLE_NAME NUM_ROWS
EMP_TARGET 5
SQL> select * from emp_target;
EMP_ID ENAME SALARY
7499 ALLEN 10040
7566 JONES 18668
7698 BLAKE 17883
7788 SCOTT 18825
7902 FORD 19825
SQL> insert into emp_target values(1345,'ROFAD',10445);
1 row created.
SQL> commit;
Commit complete.
SQL> select * from emp_target;
EMP_ID ENAME SALARY
7499 ALLEN 10040
7566 JONES 18668
7698 BLAKE 17883
7788 SCOTT 18825
7902 FORD 19825
1345 ROFAD 10445
6 rows selected.
SQL> select num_rows from user_tables where table_name ='EMP_TARGET';
NUM_ROWS
5
SQL> ANALYZE TABLE EMP_TARGET compute STATISTICS FOR TABLE;
Table analyzed.
SQL> select num_rows from user_tables where table_name ='EMP_TARGET';
NUM_ROWS
6 -
How to maintain previous and record count in audit table in SQL Server 2008 r2?
Hi Experts ,
Situation :
in our database we are having few of stored procedures which will drop and recreates the tables and it is scheduled on weekly basis. when this job will run all the stored procedures will drop all the tables and recreate. Now we need to create one table which
will maintain history of the records.
my table structure is listed below
TableName CurrentReocrdCount CurrentExecutionDate PreviousReordCount PreviousExurtiondate
TEST 1000 2014-03-30 NULL NULL
Test 1500 2014-04-10 1000 2014-03-30
Test 2000 2014-04-11 1500 2014-04-10
How do i achive this .
franklinsentilYou need to create audit tables for these. The table will be populated by COUNT value inside stored procedure. Each time it clears the main table and fills new data and also logs count details to audit tables. You can use COUNT(*) to get count value
and GETDATE function to get current execution value.
So proc will look like
CREATE PROC procname
@param....
AS
--step to drop existing table
IF OBJECT_ID('tablename') IS NOT NULL
DROP TABLE <table name>
--step to fill new table
SELECT ...
INTO TableName
FROM
--Audit table fill step
INSERT AuditTable (TableName,CurrentRecordCount,CurrentExecdate,PrevRecordCount,PrevExecDate)
SELECT TOP 1 'TableName',(SELECT COUNT(*) FROM tableName),GETDATE(),CurrentRecordCount,CurrentExecDate
FROM AuditTable
ORDER BY CurrentExecDate DESC
UNION ALL
SELECT 'TableName',(SELECT COUNT(*) FROM tableName),NULL,NULL
WHERE NOT EXISTS (SELECT 1 FROM AuditTable)
GO
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How to count records from 2 tables and show in RDLC Report
hi all,
its being a one day searching for the solution but No Luck.
I have two SQL tables tblstudetail and tblfeereceiptdetail.
i just want to count records from both tables and show in RDLC report.
I tried SQl Query Like This:
select a.session, a.course,
Count(CASE a.ADstatus WHEN 'OK' THEN 1 ELSE 0 END ) AS Admission,
Count(CASE s .I_receiptstatus WHEN 'OK' THEN 1 ELSE 0 END) AS Feeprint
from
tblstudetail a
FULL join
tblfeereceiptdetail s on s.studentID = a.studentID
where a.session = '2015' AND s.Fsession = '2015' AND a.adcat = 'Regular'
GROUP BY a.session,a.course
ORDER by a.course
The result Show the Same Value in Both columns
Session Course Admission FeeDetail
2015 B.A. I 275 275
2015 B.A. II 307 307
2015 B.A. III 255 255
2015 B.Sc. I 110 110
2015 B.Sc. II 105 105
2015 B.Sc. III 64 64
Actully I want to Count How many ADMISSION have been Taken(FROM tblstudetail) and How many FEE RECEIPT have been Print (From tblfeereceiptdetail).
please guide me for this as soon as possible.
thanks in advance...I am counting 'OK' in both the table columns I.e 'ADstatus' in tblstudetail and 'feereceiptstatus' in tblfeereceiptdetail
please suggest me -
Count total number of record of table with deletion from archiving object
Does anyone know is there any SAP standard program to count the total number of record of the table with deletion from Archiving Object and display in repprt?
Not sure of the question. Are you looking to get the sql "select count(*) from table" from using the TopLink expression framework or are you getting that SQL already and want something else?
If you are looking just to get the count from a table/class, you can use a ReportQuery:
ReportQuery rquery = new ReportQuery(ClassToQueryOn.class);
rquery.addCount(); //equivalent to count(*);
session.executeQuery(rquery);
You can use a report query to return data instead of objects, and use selection criteria just like a normal read query.
Best Regards,
Chris -
Get records count of all tables
Hi ,
I am trying to get the record count of all tables using dynamic query. I don't know how to put the value in placeholder. I tried the below code.
SET SERVEROUTPUT ON SIZE 1000000
DECLARE
CURSOR table_list
IS
select OBJECT_NAME from user_objects
where object_type in ('TABLE')
and object_name not like '%AUDIT_DDL%'
AND object_name not like 'MD_%'
AND object_name not like 'EXT_%'
AND object_name not like 'STG_%'
AND object_name not like 'SYS_%'
AND object_name not like 'TMP_%'
AND object_name not like 'TEMP_%'
order by 1;
v_count NUMBER :=0;
query_str VARCHAR2(1000);
BEGIN
FOR table_name IN table_list
LOOP
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME;
dbms_output.put_line(query_str);
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME );
v_count:= execute immediate query_str;
dbms_output.put_line('Table Name:' || table_name.OBJECT_NAME || ', Count ' || v_count );
END LOOP;
END;
I know I am doing wrong in the bold lines. But not sure how to fix it. Please help. Thanks in advance.Hi,
Welcome to the forum!
What you posted is basically right, assuming you really want to do dynamic SQL t all.
The only problem with
961618 wrote:
query_str :='SELECT COUNT(1) FROM ' || table_name.OBJECT_NAME; would be if the object name included special characters (such as single-quotes) or lower-case letters. To avoid any possible problems, I would put the object name inside double-quotes:
... query_str := 'SELECT COUNT (*) FROM "' || table_name.OBJECT_NAME
|| '"';
v_count:= execute immediate query_str;
The correct syntax is
execute immediate query_str INTO v_count;V_count will be the number of rows in a single table. Keep another variable (say total_v_count) that keeps the total count so far.
Do you really need dynamic SQL?
SELECT SUM (num_rows) AS total_rows
FROM user_tables
WHERE table_name NOT_LIKE '%AUDIT_DDL%
AND ...
;gets the same information, accurate as of the last time statistics were gathered, and some of the numbers may be approximate. Depending on how you use the results, that may be good enough for you. If you actually have 10,000,123 rows, and the query says you have 10,000,000, does it really matter? -
How to compare record count of two tables?
Hi,
i am in need of simple sql script where i can compare two table record count.
i have something like below:
(select count(*) from table1) minus (select count(*) from table2)
now the problem is if the table1 count greater then table2 count the output is fine.
If the table2 record count is more then i am getting zero as the output.
how can i get the difference in two tables record count?
Thanks a lot in advance.
--Raman.Doing a MINUS between the counts does not yield the diff.
e.g. if table A has 100 records and table B has 70 records then,
SELECT count(*) FROM A
minus
SELECT count(*) from B
will give 100 and not 30.
Try this:
SELECT (
CASE WHEN ((select count(*) cnt from A) - (select count(*) cnt from B)) <0
THEN ((select count(*) cnt from A) - (select count(*) cnt from B))* -1
ELSE ((select count(*) cnt from A) - (select count(*) cnt from B)) END) Difference
FROM dualor this is simpler
SELECT abs(((select count(*) cnt from A) - (select count(*) cnt from B))) difference FROM dualEdited by: Caitanya on Jan 9, 2009 7:12 AM
Applied abs function after seeing BluShadow's post :) -
Distinct count using lookup table
How can I get a distinct count of column values using a different table?
Let's say I want to get a distinct count of all "company_name" records in table "emp" that corespond (match) with "lookup" table, "state" category.
What I want is to find counts for all companies that have a value of "california" in the "state" column of the "lookup" Table. I want the output to look like:
Sears 17
Pennys 22
Marshalls 6
Macys 9
I want the result to show me the company names dynamically as I don't know what they are, just that they are part of the "state" group in the lookup Table. Does this make sense?
MMark,
In the future you might consider creating test cases for us to work with. Something similar to the following where sample data is created for each table as the union all of multiple select statementsselect 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual;
select 'INIT_ASSESS' rfs_category
, 1 val
from dual union all
select 'JOB_REF', 1 from dual union all
select 'JOB_REF', 1 from dual union all
select 'SPEC_STA', null from dual;Then we can either take your select statements and make them the source of a CTAS (create table as) statementcreate table lookup as
select 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual;, or include them as subfactored queries by using the with statement:with lookup as (
select 'INIT_ASSESS' lookup_type
, 1 lookup_value
, 'Initial Assessment' lookup_value_desc
from dual union all
select 'JOB_REF', 2, 'Job Reference' from dual union all
select 'SPEC_STA', 3, 'SPEC STA' from dual
), RFS as (
select 'INIT_ASSESS' rfs_category
, 1 val
from dual union all
select 'JOB_REF', 1 from dual union all
select 'JOB_REF', 1 from dual union all
select 'SPEC_STA', null from dual
select lookup_value_desc, count_all, count_val, dist_val
from lookup
join (select rfs_category
, count(*) count_all
, count(val) count_val
, count(distinct val) dist_val
from RFS group by rfs_category)
on rfs_category = lookup_type;Edited by: Sentinel on Nov 17, 2008 3:38 PM -
Counting records in Visual Composer
Hi folks,
I do have question I cannot find a solution ( maybe due to christmas turkey paralysis )
I am using VC to call a RFC function in ERP system 'RFC_READ_TABLE' to access data from table.
The table I access is a customer table containing Delta- Data
Actually the system RFC function returns all records ( normally between 1 and 10 records).
On VC side I'd like to display only the number of records to inform if new data is available.
How can I count records internally in VC?
( I do not like to bring in data directly into BI because the application I write will merge BI Query data with non BI data)
I'D like to use standard RFC function to receive data, but first hand I'd like to decide by number of entries whether to use data or not.
Any help is appreciated
TIAHi Prachi,
that's it.
I never used that functionality for plain counting records being returned by tables
It woks perfect.
The glory shiny points are yours.
Joerg -
Mysql database, counting records
Hi!
I have to store measured data to MySQL database. During this process I would like to count a number of records in a database table. It is also necessary to filter records. I'm using the SQL statement as follows:
SELECT COUNT (fieldname) AS cnt FROM table WHERE condition
Because I haven't got any result I've created a small database "mysweetdb" and table "icecream" to test my VIs (see picture bellow).
The VI is attached. The result of counting is a 2D array (DB Tools Fetch Recordset Data.VI output) with one element (one row and one column). This element contains no data.
I usually don't give up easily so I've created a similar MS ACCESS database and counted data in it. I've got a correct answer: 3. So it might be possible that there is something wrong with MySQL driver. But I've created a small Delphi project and I've counted records in MySQL database and MS ACCESS database. Both results were correct.
Can anyone explain where is the problem in communication between LabView and MySQL database?
Versions: XAMPP for Windows 1.7.3, LabView Developer Suite 2010 SP1, MySQL 5.1 ODBC driver
Thanks in advance for your suggestions.
Attachments:
Count records.vi 19 KBContDivConsult,
thank you for your answer. An updated version of my VI is attached. It uses two options: LabSQL library and DB Connectivity Toolkit. LabSQL gives correct results.
Regards,
Ljubo.
Attachments:
Count records.vi 25 KB -
Error: The sort order specified for distinct count records is incorrect
When processing a measure group with a distinct count measure in it, i get the following error:
"The sort order specified for distinct count records is incorrect."
I have no idea what this means - any ideas?I had the same problem and your fix worked. In more detail, the problematic field was contract_no. I added a named calculation to the table in the Data Source View with the formula CHECKSUM(contract_no). Then I created the distinct count measure on that named calculation. And, lo and behold, the errors disappeared!
Thank you to Frank.
- CindyCindy P Hoskey
Maybe you are looking for
-
Hi, I would like to dual boot Arch and Ubuntu using GRUB2. I already have Arch, set up as it's described in the Beginner's Guide, with GRUB2 installed. How would I go about dual booting Ubuntu, preferably without overwriting the existing bootloader?
-
My Magic Mouse Will not scroll or left click?
At 11:08 pm my magic mouse would not do anything but right click. I can not scroll either way, nor can i rightclick. I have tried System prefrences. What do i do?
-
Encrypted email in iOS / exchange domain
hi, i'm using encrypted email time to time on my PC using outlook 2012 and a smartcard.... fine my iphone is set up with this exchange account... fine I was not able to read encryted email (normal!) untill i've exported my certificate to the iphone..
-
Set Data Reporting policy?
In the latest ARD Manual (v2.2), on p. 85, it states "To set a client data reporting policy", ... choose "manage > set reporting policy". I'm using ard 3.5.1, and I do not have this option in my Manage menu, nor can I find it anywhere else. Can someo
-
(No .Mac Acct.) Can I still publish with iWeb?
I don't know much about iWeb. I already have a webpage and domain name and I am thinking of buying iLife but only if I can publish to my existing domain. Sorry if this question has already been asked but I didn't find a similar question anywhere in t