SQL -- Show results only when count's higher than xx - sql

So far I have this written:
SELECT
Query,
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2013-01-01' THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN SearchDate >= '2013-01-01' and SearchDate < '2014-01-01' THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
It looks at the query (search) terms in the table and counts how many times each appears in the given date range (in this case, this year and last).
In the results, I want to only show those that appear 100 times or more. Right now it's showing all.
Query Year2012 Year2013
beavers 90 87
hair 4 14
If the best method of doing this doesn't involve CASE WHEN, please let me know! Beginner here.

Use an additional having clause
SELECT
Query,
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2013-01-01' THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN SearchDate >= '2013-01-01' and SearchDate < '2014-01-01' THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
having
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2014-01-01'
THEN 1
ELSE 0
END) >= 100

I think this is a little clearer and easier to maintain:
SELECT
Query,
SUM(CASE WHEN year(SearchDate) = 2012 THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN year(SearchDate) = 2013 THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
having
SUM(CASE WHEN year(SearchDate) in (2012, 2013) THEN 1 ELSE 0 END)
>= 100

Related

How to display 0 in all the columns in a table when sum returned for all the columns is 0?

Currently I am getting Blank columns But I want 0 Here as shown in the image. Click here for the Image. Below is my query and I want all the columns to display 0 when sum returned is 0.
SELECT COUNT(*) AS Inserted,
SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS Pending,
SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS Completed,
SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) AS Failure
FROM [dbo].[ETIME_TIMECARD]
where cast(CreateDateTime as date) = CAST(GETDATE() AS DATE)
Group By cast(CreateDateTime as date)
You're getting no results because your WHERE isn't returning any results and you have a GROUP BY with nothing to group on. In truth, the GROUP BY appears to not be required.
SELECT COUNT(*) AS Inserted,
ISNULL(SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END),0) AS Pending,
ISNULL(SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END),0) AS Completed,
ISNULL(SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END),0) AS Failure
FROM [dbo].[ETIME_TIMECARD]
WHERE CreateDateTime >= CAST(GETDATE() AS date)
AND CreateDateTime < CAST(DATEADD(DAY, 1, GETDATE()) AS date);
Though, personally, I would switch to a COUNT as you clearly are counting, and then you don't need to ISNULL, as a COUNT will not return NULL:
SELECT COUNT(*) AS Inserted,
COUNT(CASE status WHEN 0 THEN 1 END) AS Pending,
COUNT(CASE status WHEN 1 THEN 1 END) AS Completed,
COUNT(CASE status WHEN 2 THEN 1 END) AS Failure
FROM [dbo].[ETIME_TIMECARD]
WHERE CreateDateTime >= CAST(GETDATE() AS date)
AND CreateDateTime < CAST(DATEADD(DAY, 1, GETDATE()) AS date);

Get data of 2 different dates in 2 different columns sql

I have a sql table having columns Name, VisitingDate, StayTime
I want a query which can give me data in which in 1 column I can get data of thismonthvisit and other column I can get data of lastmonthvisit and in 3rd column I can data of summation of StayTime of particular person .
Database Table : --
Name
VisitingDate
StayTime(in minutes)
A
2021-04-20
5
A
2021-04-21
15
A
2021-03-20
10
B
2021-03-20
5
Result Wanted : --
Name
Thismonthvisit
TotalStayTimeThismonth(in minutes)
LastmonthVisit
TotalStayTimelastmonth(in minutes)
A
2
20
1
10
B
0
0
1
5
Here is what you are looking for :
select name,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN 1 ELSE 0 END) AS ThisMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeThisMonth,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN 1 ELSE 0 END) AS LastMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeLastMonth
from MyTable
where FORMAT(VisitingDate, 'YYYYMM') > FORMAT(dateadd(month, -2, getdate()),'YYYYMM')
group by Name
SEE DEMO HERE
You can use aggregation:
select name,
sum(case when month(visitingdate) = month(getdate())
then 1 else 0
end) as cnt_thismonth,
sum(case when month(visitingdate) = month(getdate())
then staytime else 0
end) staytime_thismonth,
sum(case when month(visitingdate) <> month(getdate())
then 1 else 0
end) as cnt_lastmonth,
sum(case when month(visitingdate) <> month(getdate())
then staytime else 0
end) staytime_lastmonth
from t
where visitingdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
group by name;

SQL for total sales for each customer for each year

Using Advantage Database Server 11
I'm trying to find each customers total purchase from two types for comparison year by year, but I get an error:
[iAnywhere Solutions][Advantage SQL Engine]Expected
lexical element not found: THEN
Here are the table.
customernr | Date_in | Status | InvType | Qty | Total
1111 9/1/2018 D 5 25.00
1111 12/1/2018 V D 3 15.00
1111 5/12/2019 L 1 2.00
1111 7/11/2019 D 5 35.00
1112 6/21/2018 L 7 18.00
1112 9/14/2019 L 3 7.00
Select
customernr,
SUM(CASE WHEN date_in >= '2018-01-01' and date_in <= '2018-12-31' total
and InvType='D' ELSE 0 END) LastYD,
SUM(CASE WHEN date_in >= '2018-01-01' and date_in <= '2018-12-31' total
and InvType='L' ELSE 0 END) LastYL,
SUM(CASE WHEN date_in >= '2019-01-01' and date_in <= '2019-12-31' total
and InvType='D' ELSE 0 END) ThisYD,
SUM(CASE WHEN date_in >= '2019-01-01' and date_in <= '2019-12-31' total
and InvType='L' ELSE 0 END) ThisYL
from invoice
where (Status <> 'V' or Status IS NULL)
Group by Customernr
Thanks for any help,
KHJ
you have a missing THEN on your CASE statement
Select
customernr,
SUM(CASE WHEN date_in >= '2018-01-01' and date_in <= '2018-12-31'
and InvType='D' THEN total ELSE 0 END) LastYD,
SUM(CASE WHEN date_in >= '2018-01-01' and date_in <= '2018-12-31'
and InvType='L' THEN total ELSE 0 END) LastYL,
SUM(CASE WHEN date_in >= '2019-01-01' and date_in <= '2019-12-31'
and InvType='D' THEN total ELSE 0 END) ThisYD,
SUM(CASE WHEN date_in >= '2019-01-01' and date_in <= '2019-12-31'
and InvType='L' THEN total ELSE 0 END) ThisYL
from invoice
where (Status <> 'V' or Status IS NULL)
Group by Customernr

SQL COUNT column where value is greater than value

I have a basic select query that is looking at some sample data in my table. I am trying to get three pieces of information.
Total Samples (total records)
How many with a Score greater than or equal to 85
How many with a Score less than 85
Data:
ScoreID RecordID Score ErrorMarkedToQID ErrorActionID
1 2 30 Q00019 1
2 2 100 Q20039 3
3 3 30 Q10091 3
4 3 35 Q00019 5
6 4 5 Q10091 3
This is what I attempted:
DECLARE #startDate DATE = '2018/09/12', #endDate DATE = '2018/09/24'
SELECT COUNT(s.ScoreID) AS totalSamples,
COUNT(CASE WHEN s.Score >= 85 THEN 1 ELSE 0 END) AS Pass,
COUNT(CASE WHEN s.Score < 85 THEN 1 ELSE 0 END) AS Fail
FROM [SubmissionScores] AS s
JOIN Submission AS sub
ON sub.SubmissionID = s.RecordID
WHERE sub.DateSubmittedUTC BETWEEN #startDate AND #endDate
My current output is that all fields are outputting 5 which is the total number of records. So it seems like my CASE logic isn't correct.
Can this be done in a simple query like I am attempting?
DECLARE #startDate DATE = '2018/09/12', #endDate DATE = '2018/09/24'
SELECT COUNT(s.ScoreID) AS totalSamples,
COUNT(CASE WHEN s.Score >= 85 THEN 1 ELSE NULL END) AS Pass,
COUNT(CASE WHEN s.Score < 85 THEN 1 ELSE NULL END) AS Fail
FROM [SubmissionScores] AS s
JOIN Submission AS sub
ON sub.SubmissionID = s.RecordID
WHERE sub.DateSubmittedUTC BETWEEN #startDate AND #endDate
The Count() function will return the number of rows that match a specified criteria, but your Case() has a result for both match and no match, so it returns the same (total) number of rows in all case
with Case() 0 or 1 you can use sum() which will summarize the result of the case
DECLARE #startDate DATE = '2018/09/12', #endDate DATE = '2018/09/24'
SELECT COUNT(s.ScoreID) AS totalSamples,
SUM(CASE WHEN s.Score >= 85 THEN 1 ELSE 0 END) AS Pass,
SUM(CASE WHEN s.Score < 85 THEN 1 ELSE 0 END) AS Fail
FROM [SubmissionScores] AS s
JOIN Submission AS sub
ON sub.SubmissionID = s.RecordID
WHERE sub.DateSubmittedUTC BETWEEN #startDate AND #endDate

Group by year in sql

I am trying to group by year but was not able to do.I can get the column count but not year wise. this is what i tried.
select t_contract ,
sum(CASE t_contract when '18' then 1 else 0 end) as XL,
sum(CASE t_contract when '01' then 1 else 0 end) as VC,
sum(CASE t_contract when '75' then 1 else 0 end) as AN,
sum(CASE t_contract when '48' then 1 else 0 end) as CS
from icps.dbo.tickets
WHERE
t_date_time_issued >= DATEADD(year, -6, GETDATE())
GROUP BY contract
.. but i want to add year .. where i have t_date_time _issued column.
My another query is I have a column called t_zone_name and I want to sum all the rows where t_zone_anme like '%ICeland%' an i tried this:
sum(CASE t_zone_name like '%ICeland%' then 1 else 0 end) as ICELAND
but I get an error on statement like... thanks in advance.
LIKE
YEAR XL VC AN CS total
2010 50 50 50 50 200
2011 5 5 5 5 20
Try the below query:
SELECT t_contract, YEAR(t_date_time_issued) As Yr, SUM(CASE WHEN t_zone_name like '%ICeland%' THEN 1 ELSE 0 END) AS ICELAND
SUM(CASE t_contract when '18' then 1 else 0 end) as XL,
SUM(CASE t_contract when '01' then 1 else 0 end) as VC,
SUM(CASE t_contract when '75' then 1 else 0 end) as AN,
SUM(CASE t_contract when '48' then 1 else 0 end) as CS
FROM icps.dbo.tickets
WHERE YEAR(t_date_time_issued) >= (YEAR(GetDate()) - 6)
GROUP BY t_contract, YEAR(t_date_time_issued)
You might need change the order of t_contract and YEAR(t_date_time_issued) depending on which grouping you want to apply first.
As suggested by #ray I have replaced DATEPART(yyyy, t_date_time_issued) >= DATEPART(yyyy, DATEADD(year, -6, GETDATE())) with year(t_date_time_issued) >= (year(GetDate()) - 6)
If you want to group by year, in sql server, you might
GROUP BY DATEDIFF(year,t_date_time_issued, GETDATE())
In other DB engine, usually has method to get year part, or use substring to get year part from a time string.