Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the sum of a count column in SQL

I have the following query

SELECT 
    dtc.coupon_type_company_name,  
    COUNT(*) * dtc.coupon_type_company_coupon_amount AS 'Total_Coupon_To_Be_Used',
    dtc.coupon_type_company_coupon_months_combinable
FROM 
    [dbo].[coupon_type_Company_User] dtcu
JOIN 
    coupon_type_Company dtc ON dtcu.coupon_type_Company_ID = dtc.id
JOIN 
    person p ON dtcu.userID = p.userID
WHERE 
    coupon_type_company_coupon_is_combinable = 1 
    OR coupon_type_company_has_coupon = 1 
    AND dtc.companyID = 1081
    AND p.is_active = 1
GROUP BY
    dtc.coupon_type_company_name,dtc.coupon_type_company_coupon_amount,
    dtc.coupon_type_company_coupon_months_combinable

This returns the following:

enter image description here

What I want to have however is just one column and one row that should take the SUM of my middle column (count(*)*dtc.coupon_type_company_coupon_amount).

How could I achieve this and prevent doing this in my code backend (C#)

like image 783
user3127554 Avatar asked Mar 06 '23 19:03

user3127554


1 Answers

You can wrap your query like this:

SELECT SUM(Total_Coupon_To_Be_Used) AS the_sum
FROM (
   your query
) s
like image 106
Eric Avatar answered Mar 09 '23 00:03

Eric