SQL Server : how to get DISTINCT COUNT for every GROUP - sql-server

I have a table like this:
I would like to get the distinct counts for every GROUP:
How to get the result? Thank you.

You can use conditional aggregation:
select group,
sum(case when location = 'A' then 1 else 0 end) as a,
sum(case when location = 'B' then 1 else 0 end) as b,
sum(case when location = 'C' then 1 else 0 end) as c
from t
group by group;
Note that group is a very poor name for a column because it is a SQL reserved word.

Related

Sum of a column in snowflake

I have two calculated columns with case statements. Now, I need to take Sum of those columns and need the difference in it.
For Ex.
Select Case when account = '30' and status='active' then value as value1,
case when account = '31' and status='active' then value as value2,
Sum(value1) - Sum(Value2) as Total_SUM
from table
How can we achieve this.. This gives me a missing group by clause error. I tried many things but did not work out.
Use conditional aggregation and sum the CASE expressions:
SELECT
SUM(CASE WHEN account = '30' THEN value ELSE 0 END) AS value1,
SUM(CASE WHEN account = '31' THEN value ELSE 0 END) AS value2,
SUM(CASE WHEN account = '30' THEN value ELSE 0 END) -
SUM(CASE WHEN account = '31' THEN value ELSE 0 END) AS Total_SUM
FROM yourTable
WHERE status = 'active';

"having" clause to filter students' sate of residence where count of Male > Female

Please see the following query:
select
s.state
from
students as s
group by
s.state
having
count(case when s.gender = 'M' then 1 else 0 end) > count(case when s.gender = 'F' then 1 else 0 end)
This query will run but returns nothing. I'm trying to select & group by state where the count of males is greater than that of females. What is the issue with the query?
I should be using sum, instead of count. Dumb mistake...

Subract one aggregate value from another

I'm writing a query to aggregate bookings for an event, and to then split the total figure into two categories: a count of those people with an application, and a count of those without an application.
Calculating the total booking figure and the number of applicants is no problem - the code I'm using is as follows:
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...
However, I'm having problems with calculating the count of people that do not have an application (i.e. they have no application record associated with their account). I've tried using a NOT EXISTS statement, but discovered that this won't work within an aggregate statement.
So, what I'm instead trying to do is simply subtract the 'Number of Applicants' from the 'Total Bookings' figure, as this will leave me with a count of the number of non-applicants.
I've tried to simply subtract the above two outputs using the line of code below:
SUM ('Total Bookings' - 'Current Applicants') 'Non-Applicants'
But this gives me the error:
"Msg 8117, Level 16, State 1, Line 4
Operand data type varchar is invalid for subtract operator."
I'm presuming I need to get the earlier output to cast as an Integer - please can anyone help me with the syntax?
You can't use column aliases from your calculations directly in the same query, you could use your current SELECT as a derived table, or a CTE, or simply derive your new calculation. Also, you should avoid using single quotes for table aliases, instead use []:
SELECT [EVENTMODULE].[DESCRIPTION] as [Event],
CAST([EVENTMODULE].[STARTDATE] as DATE) as [Event Date],
SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') THEN 1 ELSE 0 END) [Total Bookings],
SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' THEN 1 ELSE 0 END) [Current Applicants],
SUM(CASE WHEN [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND ISNULL([COURSEPLACE].[TYPE],'') <> 'Application' THEN 1 ELSE 0 END) [Non-Applicants]
...
Use Square Brackets to escape the space in column names. Single quotes will make it as string constant
select SUM ([Total Bookings] - [Current Applicants]) 'Non-Applicants'
from
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants'
..
)
Note : When you are using Single quotes to escape the space in alias name it will work but it will not work when using it as column names
Hope this helps
with cte as
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end)
)
select Event,Event Date,Total Bookings,[Total Bookings]-[EVENTPLACE].[STATUS] AS 'Non-Applicants'
from cte
Try this:
SELECT * , [Non-Applicants] = [Total Bookings] - [Current Applicants]
FROM
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...
) A

SQL Server Query that returns the number of Likes and number of Dislikes

I have a SQL server table that displays what a user Liked or Disliked in an item description. He/she can only like/dislike one item so it will display a 1 if Liked or 0 if Disliked on the Type Field.
What I want is for an output that counts the Likes and Dislikes that displays both of them as seen below. I tried to do inner joins and unions and can't get it to work. Any ideas?
SELECT ItemID,
Description,
SUM(CASE WHEN Type = 1 THEN 1 ELSE 0 END) AS Like,
SUM(CASE WHEN Type = 0 THEN 1 ELSE 0 END) AS Dislike
FROM Table
GROUP BY ItemID,
Description
try:
select ItemId,Description, sum(case when Type=1 then 1 else 0 end) 'like', // quote the word like
sum(case when Type = 0 then 1 else 0 end) 'dislike'
from tblFeedback
group by ItemId

SQL Server - need assistance with sum and case statements

I'm using SQL Server 2005. I'm looking to add up the columns (AM, Midday, Evening) to see which ones contains the value "YES" and then take that total and multiply it by the rate for each row for a client.
Here is the query I have so far:
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
with the following output
am_total midday_total
45 49
When I introduce the rate variable, my query starts telling me I need the group_by clause and I don't think I'm ready for that since I still need to add the am_total and the midday_total together first and then multiply that by the rate.
Ultimately, all I'm looking for is the grand total.
If I understand your question, maybe this is what you need
declare #rate int
set #rate = 2 /*what ever rate is */
select am_total * #rate as am, midday_total * #rate as midday
from (
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
)
You can also join another table and use its columns in calculation
Select
Sum(Case When morning = 'yes' Then 1 * u.rate Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 * u.rate Else 0 End) midday_total
From services srv inner join users u on services.id = u.service_id -- assuming this is relation
pay attention on u.rate above

Resources