exclude some data from a table SSRS - sql

I want to exclude the weekend and the holiday from my table:
for example in this picture I would like to exclude the date 19.01. and 10.01 from my table or it should show only 0 in 10.01.2016.
this is my code:
SELECT *
FROM (
Select intervaldate as Datum, tsystem.Name as Name,
SUM(case when Name = 'Maschine 1' then Units else 0 end) as Maschine1,
Sum(case when Name = 'Maschine 2' then Units else 0 end) as Maschine2,
Sum(case when Name = 'Maschine 3' then Units else 0 end) as Maschine3,
from Count inner join tsystem ON Count.systemid = tsystem.id
where IntervalDate BETWEEN #StartDateTime AND #EndDateTime
and tsystem.Name in ('M101','M102','M103','M104','M105','M107','M109','M110', 'M111', 'M113', 'M114', 'M115')
group by intervaldate, tsystem.Name
) as s

I think the best approach is create a table in your database and store all weekend and holidays dates then use that table to filter your query.
Something like this:
SELECT *
FROM (
Select intervaldate as Datum, tsystem.Name as Name,
SUM(case when Name = 'Maschine 1' then Units else 0 end) as Maschine1,
Sum(case when Name = 'Maschine 2' then Units else 0 end) as Maschine2,
Sum(case when Name = 'Maschine 3' then Units else 0 end) as Maschine3,
from Count inner join tsystem ON Count.systemid = tsystem.id
where IntervalDate BETWEEN #StartDateTime AND #EndDateTime
and IntervalDate NOT IN (select WeekendOrHolidayDate from MyWeekendAndHolidayTable)
and tsystem.Name in ('M101','M102','M103','M104','M105','M107','M109','M110', 'M111', 'M113', 'M114', 'M115')
group by intervaldate, tsystem.Name
) as s
The below query will exclude weekdays only. There is no way to produce holidays from SQL if you want to exclude also holidays you have to store it somewhere in your database.
SELECT *
FROM (
Select intervaldate as Datum, tsystem.Name as Name,
SUM(case when Name = 'Maschine 1' then Units else 0 end) as Maschine1,
Sum(case when Name = 'Maschine 2' then Units else 0 end) as Maschine2,
Sum(case when Name = 'Maschine 3' then Units else 0 end) as Maschine3,
from Count inner join tsystem ON Count.systemid = tsystem.id
where IntervalDate BETWEEN #StartDateTime AND #EndDateTime
and ((DATEPART(dw, IntervalDate) + ##DATEFIRST) % 7) NOT IN (0, 1)
and tsystem.Name in ('M101','M102','M103','M104','M105','M107','M109','M110', 'M111', 'M113', 'M114', 'M115')
group by intervaldate, tsystem.Name
) as s
Let me know if this helps you.

For excluding weekend...you can use date function and IIF condition. If week number is 7 or 1 then exclude in report...You can do this by right click on report properties and choose filter..

Right click the row group in your tablix and select Row Visibility. In the Change display options, select Show or hide based on an expression. In the expression, this should work:
=iif(CDate(Fields!Date.Value).DayOfWeek = DayOfWeek.Saturday, true, iif(CDate(Fields!Date.Value).DayOfWeek = DayOfWeek.Sunday, true, false))
If there's a ton of data, for performance reasons I'd recommend trimming these rows on the database side.

Related

A SQL query for the retrieval of result based on input month

Table 1
Table 2
My requirement is to input the Redemption month and list the tickets that has been scanned double or more.
For example Ticket No. T1 has been scanned 2 times under pickup,only once under PickupOutforDelivery and 2 times under Delivery.
Result needed like this:
How can I write a query to get the result like this?
Tried:
SELECT
Ticket,
COUNT(Scantype = 0) AS Pickup,
COUNT(Scantype = 1) AS PickupOutforDelivery,
COUNT(Scantype = 2) AS Delivery
FROM
Scans
GROUP BY
Ticket, ScanType
HAVING
(Pickup > 1 OR PickupOutforDelivery > 1 OR Delivery > 1)
OR (Pickup >= 1 AND PickupOutforDelivery >= 1)
ORDER BY
Ticket
Result
Assuming that RedemptionMonth has a datatype of DATE (which is clearly required); the following query will give you the result you want, except the "cosmetic" part (breaking by year month for the report part) that you have to do on your application:
SELECT YEAR(RedemptionMonth) AS [YEAR], MONTH(RedemptionMonth) AS [MONTH], TicketNo,
COALESCE(SUM(CASE WHEN ScanName = 'Pickup' THEN 1 ELSE 0 END), 0) AS Pickup,
COALESCE(SUM(CASE WHEN ScanName = 'PickupOutForDelivery' THEN 1 ELSE 0 END), 0) AS PickupOutForDelivery ,
COALESCE(SUM(CASE WHEN ScanName = 'Delivery' THEN 1 ELSE 0 END), 0) AS Delivery
FROM [Table 1] AS T1
JOIN [Table 2] AS T2
ON T1.ScanType = T2.ScanType
GROUP BY YEAR(RedemptionMonth) AS [YEAR], MONTH(RedemptionMonth) AS [MONTH], TicketNo
Because you are using the numeric value of scanType, no JOIN is needed. So, the only fix is needed for conditional aggregation:
SELECT Ticket,
SUM(CASE WHEN Scantype = 0 THEN 1 ELSE 0 END) as Pickup,
SUM(CASE WHEN Scantype = 1 THEN 1 ELSE 0 END) as PickupOutforDelivery,
SUM(CASE WHEN Scantype = 2 THEN 1 ELSE 0 END) as Delivery
FROM Scans
WHERE redemptionMonth = 'Jan-21'
GROUP BY Ticket
HAVING Pickup > 1 OR
PickupOutforDelivery > 1 OR
Delivery > 1 OR
(Pickup >= 1 AND PickupOutforDelivery >= 1)
ORDER BY Ticket;
Note that you can add redemptionMonth to the GROUP BY (and SELECT) to get the results for each month.
If redemptionMonth is really a date and not a string, then define the time period using a range of dates:
WHERE redemptionMonth >= '2021-01-01' AND
redemptionMonth < '2021-02-01'

How to remove rows that are all zeros from SQL query

Should be simple to do this but cannot make it work. Have also looked at other similar answers. This code generates a report. There are 3 primary categories: General Adjustments, Finance Charges, and Bad Debts. What I am trying to accomplish...
If these 3 columns are all zeros in a row, delete that row. That's it.
DECLARE #startdate DATETIME
DECLARE #lastdate DATETIME
SET #startdate = '20170701'
SET #lastdate = '20170731'
CREATE TABLE #a
(
ClientName VARCHAR(50),
JobName VARCHAR(50),
JobPartner VARCHAR(40),
[Date] DATETIME,
GenAdj MONEY,
FC MONEY,
BadDebt MONEY,
nomid INT
)
SELECT
C.searchname AS 'CLIENT NAME',
n.date AS 'DATE',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=2 THEN TOTAL else 0 END) AS 'GENERAL ADJUSTMENTS',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=1 THEN TOTAL else 0 END) AS 'FINANCE CHARGES',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=0 THEN TOTAL else 0 END) AS 'BAD DEBTS',
sl.serviceline AS 'DEPARTMENT',
p.name AS 'PARTNER NAME'
FROM
tblNominal N
JOIN
tblNominalAccs A ON N.ContNominalID = A.NominalID
JOIN
tblclient C on N.clientid = C.clientid
LEFT JOIN
tbljob j ON n.jobid = j.JobID
LEFT JOIN
tblpartner p ON j.PartnerID = p.PartnerID
LEFT JOIN
tbljobtype jt ON j.jobtypeid = jt.jobtypeid
LEFT JOIN
tblserviceline sl ON j.servicelineid = sl.servicelineid
WHERE
Date >= #startdate AND DATE <= #LASTDATE
GROUP BY
C.searchname, n.date, sl.serviceline, p.name
ORDER BY
'CLIENT NAME' asc, 'FINANCE CHARGES' asc
DROP TABLE #a
I think I may be overthinking this. How can I delete the rows with all zeros?
Thank you for reading.
You need to use a HAVING clause after your GROUP BY but before your ORDER BY:
HAVING SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=2 THEN TOTAL else 0 END) > 0
OR SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=1 THEN TOTAL else 0 END) > 0
OR SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=0 THEN TOTAL else 0 END) > 0
HAVING is kind of like a WHERE for group results.

SSRS: how to get top 3 in order Z to A

I try to get in my diagram the top 3 of the worst value in SSRS:
my Code:
SELECT *
FROM (
Select top 3
intervaldate as Datum
,Name
,teamname as Team
,SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown
,Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown
,Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
) c
Expression of the diagram:
=Sum(Fields!Blown.Value + Fields!Thrown.Value) / Sum(Fields!Total.Value) * 100
And I sorted it from highest to lowest
But it does not show me the right order.
If I choose every "Name" then it shows me other value then the top 3:
all Names with value:
top 3:
It's because your top 3 statement is in the SQL while your sort is in the report. Without an order by SQL picks the top 3 random records. Also, unless there is more SQL you are not showing, the outer select is unnecessary. Add an order by <column> desc below your group by.
with Calcs as
(
select intervaldate as Datum,
Name,
TeamName,
SUM(case when CounterName = 'Blown away' then calculationUnits else 0 end) as Blown,
Sum(case when CounterName = 'Thrown away' then calculationUnits else 0 end) as Thrown,
Sum(case when CounterName = 'total' then calculationUnits else 0 end) as Total
from Counting
where IntervalDate >= dateadd(day,datediff(day,1,GETDATE()),0)
AND IntervalDate < dateadd(day,datediff(day,0,GETDATE()),0)
and Name in (Select SystemID from tSystemView where SystemViewID = 2)
group by intervaldate, teamName, Name
)
select b.*
from
(
select a.*, row_number() over (order by (Blown + Thrown)/Total desc) as R_Ord -- Change between ASC/DESC depending on needs
from Calcs a
) b
where R_Ord <=3

Divide and sum in SQL

I got this code and in this code I do a sum of the slow and fast driver. My Problem is I must divide this sum with the normal driver. I donĀ“t know how I can do a division in this statement:
Select *
FROM (
Select date as Datetime, tevent.name as Event, level = case
when levelname = 'High' then 'High'
when levelname = 'Normal' then 'Normal'
when shiftname = 'Low' then 'Low'
end, SUM(value) as sum
from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('Drive Fast', 'Drive Slow')
and date > getdate() -1
and tevent.Name in ('E01','E02','E03','E04','E05','E06','E07','E08')
and CalName = 'Drive'
group by tevent.name, date, levelname
) as s
PIVOT
(
SUM(sum)
FOR Event IN (E01,E02,E03,E04,E05,E06,E07,E08)
) as p
order by Datetime, level
And Then I put the same Select statement with the normal driver :
... from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('drive normal') ...
And I would like to make a division like this:
(Sum('drive fast' + 'drive slow')/Sum('drive normal')) * 100
There is a simpler way to include different cases in different sums inside a SQL statement: sum a case, like in the below calculation of percent:
Select ...
, SUM(case Name
when 'drive fast' then Value
when 'drive slow' then value
else 0 end)
/ SUM(case Name
when 'drive normal' then value
else 0 end) * 100 as percentage
from ...
where ...
group by ...;
As I lack data to test this code, I created a query on the CARS table SAS delivers as training material, implementing the same principle.
select Cylinders
, sum(case origin when 'USA' then EngineSize
when 'Asia' then EngineSize
else 0.0 end)
/ sum(case origin when 'Europe' then EngineSize
else 0.0 end)
* 100 as percentage
from sasHelp.cars
where Cylinders in (4, 5, 6, 12)
group by Cylinders

SQL Query: Cannot perform aggregate functions on sub queries

I have the following SQL query
SELECT
[Date],
DATENAME(dw,[Date]) AS Day,
SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 1) THEN Units ELSE 0 END) ChargeableTotal,
SUM(CASE WHEN ChargeCode IN (SELECT ChargeCode FROM tblChargeCodes WHERE Chargeable = 0) THEN Units ELSE 0 END) NotChargeableTotal,
SUM(Units) AS TotalUnits
FROM
tblTimesheetEntries
WHERE
UserID = 'PJW'
AND Date >= '2013-01-01'
GROUP BY
[Date]
ORDER BY
[Date] DESC;
But I get the error message:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Because I am using sub queries in the Case Else Summation.
How can I revise my query to get 2 x Sums of [Units] one for Chargeable = true, and one for Chargeable = false, even though the Chargeable field is in a different table to all the other information. The two tables are linked by ChargeCode which appears in both tblTimesheetEntries and tblChargeCodes.
Have you tried joining the tables on the chargeCode:
SELECT e.[Date],
DATENAME(dw,e.[Date]) AS Day,
SUM(CASE WHEN c.Chargeable = 1 THEN e.Units ELSE 0 END) ChargeableTotal,
SUM(CASE WHEN c.Chargeable = 0 THEN e.Units ELSE 0 END) NotChargeableTotal,
SUM(e.Units) AS TotalUnits
FROM tblTimesheetEntries e
LEFT JOIN tblChargeCodes c
on e.ChargeCode = c.ChargeCode
WHERE e.UserID = 'PJW'
AND e.Date >= '2013-01-01'
GROUP BY e.[Date]
ORDER BY e.[Date] DESC;