Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count with inner join sql query

Tags:

Hi all we have got two tables "Subscriptioninfo , activationinfo" and the structure is like this for the two tables

Subscriptioninfo table

   cert_id (int, PK)
   customer_email(string)
   subscription_key(string)
   activated_on (datetime)

activationinfo Table:

    cert_id (int)
    activationcode(string)
    subscription_key(string , FK)
    activated_ts(datetime)

the below query will give the count as "one" if an entry to Subscriptioninfo with the same year and customer email ID (this is fine)

SELECT COUNT(*) FROM Subscriptioninfo WITH (NOLOCK)
WHERE year(activated_On) = year(getdate()) AND customer_email =@CustomerEmail

we have one sp that will insert the data into both the tables (i.e) one entry to Subscriptioninfo where as four entries to activationinfo

I need to return count as "0" if one entry to subscriptioninfo and two entries to activationinfo

and i need to return count as "1" if one entry to subscriptioninfo and four entries to activationinfo..

Would any one please help on this query how can i get that count with join clause..

Many thanks in advance...

tried with this query but it is giving the activationinfo entry count(i.e) 4 instead of 1

 SELECT COUNT(*) FROM subscriptioninfo csi join activationinfo aci on csi.subscription_key = aci.subscription_key
 WHERE year(Activated_On)  = year(getdate()) AND customer_email = '[email protected]' group by csi.subscription_key
like image 942
Glory Raj Avatar asked Apr 19 '16 09:04

Glory Raj


People also ask

How do I join two tables and counts in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.

Can we use select inside count?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

What does count (*) do in SQL?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.


1 Answers

Use CASE statements

SELECT CASE WHEN COUNT(*) = 4 THEN 1
            WHEN COUNT(*) < 4 THEN 0
       END CountResults
FROM subscriptioninfo csi 
join activationinfo aci on csi.subscription_key = aci.subscription_key
WHERE year(Activated_On)  = year(getdate()) AND customer_email = '[email protected]' group by csi.subscription_key
like image 135
Vignesh Kumar A Avatar answered Sep 28 '22 01:09

Vignesh Kumar A