Update To 0 when Count Is 0 Not Display Null - sql-server-2008-r2

I am running this update query, and I was hoping it would update the table to hold a value of 0 instead of displaying NULL when the count is 0. How can this be updated to force the table so show a 0 when the count returned is 0?
set #sql =
'UPDATE cra
SET mastercounts = te.LC
FROM #tbl_test As cra
JOIN (
select
,COUNT(CASE WHEN recordID < 1 THEN 0 ELSE recordID end) As LC
,employeename
from productioninformaiton
where salestatus = (''Approved'', ''Shipped'')
Group By employeename
) As te
ON cra.[StoreName] = te.[StoreName]
AND cra.[employeename] = te.[employeename]'
Exec (#sql)

Maybe the field "recordID" is returning NULL in some cases, which makes COUNT(NULL) return NULL as well. Try replacing
COUNT(CASE WHEN recordID < 1 THEN 0 ELSE recordID end) As LC
with
COUNT(CASE WHEN ISNULL(recordID, 0) < 1 THEN 0 ELSE ISNULL(recordID, 0) end) As LC

Related

Postgresql count from multiple columns in a row

I have this table on a postgres db (proofs). proof_1, proof_2 and proof_3 are boolean columns indicating whether the user (user_id) has submitted the proofs:
user_id
proof_1
proof_2
proof_3
1
true
true
false
2
true
false
false
3
true
true
true
I need to count how many proofs are submitted by each user. This is the query that I came up:
> select
user_id,
length(
concat(
case when proof_1 then '1' end,
case when proof_2 then '1' end,
case when proof_3 then '1' end)
)) as proof_counts
from
proofs
The query above would work. But I don't think that it is the best query to do. Please advice on what query should be done?
select user_id,
case when proof_1 then 1 else 0 end
+ case when proof_2 then 1 else 0 end
+ case when proof_3 then 1 else 0 end as proof_counts
from (
values (1,true,true,false), (2,false,true,false)
) as proof (user_id, proof_1, proof_2, proof_3)
If there is no null values then below query
select user_id,
proof_1::integer
+ proof_2::integer
+ proof_3::integer as proof_counts
from (
values (1,true,true,false), (2,false,true,false)
) as proof (user_id, proof_1, proof_2, proof_3)
And version which handle nulls
select user_id,
coalesce(proof_1::integer,0)
+ coalesce(proof_2::integer,0)
+ coalesce(proof_3::integer,0) as proof_counts
from (
values (1,null,true,false), (2,false,true,false)
) as proof (user_id, proof_1, proof_2, proof_3)
I think this is also a good alternative:
select user_id,
sum(case when proof_1 = true then 1 else 0 end) + sum(case when proof_2 = true then 1 else 0 end) + sum(case when proof_3 = true then 1 else 0 end) as proof_counts
from proofs
group by user_id
This is possible just by converting your boolean to integer and then summing the three columns
Query:
select
userid_id,
sum(case when proof_1=true then 1 end)+sum(case when proof_2=true then 1 end)+sum(case when proof_2=true then 1 end) as total_proofs_submitted
from proofs
group by user_id

Selecting multiple counted fields in T-SQL query

I am stuck on a SQL query, where I need to count the number of different values in a field.
My query is:
SELECT
Area
, (SELECT count(TestResult) FROM TestRun WHERE TestResult = 'PASS' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [Passed]
, (SELECT count(TestResult) FROM TestRun WHERE TestResult = 'FAIL' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [Failed]
, (SELECT count(TestResult) FROM TestRun WHERE TestResult = 'NOTRUN' AND TestRun.CreatedDate > '2019-11-18 01:00:00') as [NotRun]
FROM TestRun
WHERE dbo.TestRun.CreatedDate > '2019-11-18 01:00:00'
GROUP BY dbo.TestRun.Area, TestRun.TestResult, TestRun.CreatedDate
But The Results I get back look like this, instead of individual values:
You can create your own fields using case and then sum them.
SELECT Area
, SUM(CASE WHEN TestResult = 'PASS' THEN 1 ELSE 0 END) AS Passed
, SUM(CASE WHEN TestResult = 'FAIL' THEN 1 ELSE 0 END) AS Failed
, SUM(CASE WHEN TestResult = 'NOTRUN' THEN 1 ELSE 0 END) AS NotRun
FROM TestRun
WHERE CreatedDate > '2019-11-18 01:00:00'
GROUP BY Area

Count distinct column case when/conditional

I'm trying to count the distinct number of ids in a column and this works fine.
COUNT(DISTINCT messages.id) AS link_created
But when I try to count with a conditional, I get a syntax error, what's the proper syntax to add a case when or some other condition to only count the distinct message ids where the messages.link_label is present?
COUNT(DISTINCT messages.id CASE WHEN messages.link_label IS NOT NULL 1 END) AS link_created
My full query looks like this.
#customers = Customer.select("customers.*,
COUNT(DISTINCT recipient_lists.id) messages_sent,
COUNT(DISTINCT messages.id CASE WHEN messages.link_label IS NOT NULL 1 END) AS link_created,
COALESCE(SUM(video_activities.video_watched_count),0) AS watched_count,
COALESCE(SUM(video_activities.response_count),0) AS response_count,
COALESCE(SUM(video_activities.email_opened_count),0) AS email_opened_count,
COALESCE(SUM(CASE WHEN video_activities.video_watched_at IS NOT NULL THEN 1 ELSE 0 END),0) AS unique_watches,
COALESCE(SUM(CASE WHEN video_activities.email_opened_at IS NOT NULL THEN 1 ELSE 0 END),0) AS unique_opens,
COALESCE(SUM(CASE WHEN video_activities.response_count > 0 THEN 1 ELSE 0 END),0) AS unique_responses,
customers.updated_at AS last_login,
SUBSTRING( email from POSITION( '#' in email) + 1 for length(email)) AS company")
.joins("LEFT JOIN messages ON customers.id = messages.customer_id
LEFT JOIN recipient_lists ON messages.id = recipient_lists.message_id AND messages.link_label is NULL
LEFT JOIN video_activities ON messages.id = video_activities.message_id")
.group("customers.id")
Try this:
COUNT(DISTINCT CASE
WHEN messages.link_label IS NOT NULL
THEN messages.id
ELSE NULL END)
AS link_created

Count based on Or is not differentiating the count

My results are showing both counts the same but there should be some that have different counts as CarCode is sometimes null.
SELECT distinct car.carKey,
car.Weight,
car.CarCode,
COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
COUNT(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode
then 0
else car.carKey End) OVER(PARTITION BY car.carKey) AS CarCount
from car
results show TotalCarKeyCount and CarCountWithoutCode always with the same counts like the case statement isn't working or something.
It sounds like you might want to use SUM() instead:
SELECT distinct car.carKey,
car.Weight,
car.CarCode,
COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
SUM(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode
then 0 else 1 End) OVER(PARTITION BY car.carKey) AS CarCount
from car
SQL Fiddle demo showing the difference between using COUNT() and SUM():
create table test
(
id int
);
insert into test values
(1), (null), (23), (4), (2);
select
count(case when id is null then 0 else id end) [count],
sum(case when id is null then 0 else 1 end) [sum]
from test;
Count returns 5 and Sum returns 4. Or you can change the COUNT() to use null and the null values will be excluded in the final count()
select
count(case when id is null then null else id end) [count],
sum(case when id is null then 0 else 1 end) [sum]
from test;
Your query would be:
SELECT distinct car.carKey,
car.Weight,
car.CarCode,
COUNT(car.carKey)OVER(PARTITION BY car.carKey) AS TotalCarKeyCount,
COUNT(Case When (car.[Weight] IS not null) and (car.CarCode is null) as CarCountWithoutCode
then null else 1 End) OVER(PARTITION BY car.carKey) AS CarCount
from car
Change the then 0 to then null. Zero values are counted, nulls are not.

Speed up plpgsql that counts doc types in a loop?

Is there a way to speed up our plpgsql function that counts certain types of docs all in one query which is executed in a loop? ALL in one query?
validador := (select count(id_doc) from webdte.doc_tip_cifra
where id_doc = id_documento and id_tipo_cifra = 901);
validador2 := (select count(id_doc) from webdte.doc_tip_cifra
where id_doc = id_documento and id_tipo_cifra = 902);
validador3 := (select count(id_doc) from webdte.doc_tip_cifra
where id_doc = id_documento and id_tipo_cifra = 905);
validador4 := (select count(id_doc) from webdte.doc_tip_cifra
where id_doc = id_documento and id_tipo_cifra = 907);
It should be faster to assign all four variables in one query (only one table or index scan):
SELECT INTO validador, validador2, validador3, validador4
sum(CASE id_tipo_cifra WHEN 901 THEN 1 ELSE 0 END)
,sum(CASE id_tipo_cifra WHEN 902 THEN 1 ELSE 0 END)
,sum(CASE id_tipo_cifra WHEN 905 THEN 1 ELSE 0 END)
,sum(CASE id_tipo_cifra WHEN 907 THEN 1 ELSE 0 END)
FROM webdte.doc_tip_cifra
WHERE id_doc = id_documento;
Same result.
Normally you would have to check id_doc for NULL in addition, but since you have a WHERE condition with = on it, it cannot be NULL.