Parameter to find all records or exclude NULL - tsql

I have found several articles on how to accomplish the reverse of what I want to do with several methods (IS NULL, CASE, COALESCE), but I think at this point I am more confused than ever after reading all this and probably making solution harder than it needs to be. I am new to T-SQL and I am currently using VS 2005 to build a basic medical report.
I have the Date Range parameter working properly by using a convert command to ignore time stamp giving me all records for the day or date range. I am now wanting to filter SSRS reprot by perliminary report date to find records with preliminary report, or, all records in table.
The database has NULL if no preliminary report was created
The database has time stamp if preliminary report was created. (showing date and time it was created)
I need to find all records not NULL, or all records. (using a parameter)
I have a parameter "Display Prelim Reports only?" #PrelimOnly with a YES or NO answer.
If I use the following it will show all records correctly (all records not NULL showing only records with Prelim report/time stamp present)
LIS_Results.Prelim_Report_Date <> '#PrelimOnly' ----User selects YES it passes NULL
however, if user selects NO, how would I get it to display all records including NULL?
Thank you for any help
Thank you both for your help, it was ultimately a combination of both that got it going. Syntax is as follows.
WHERE (#PrelimOnly = 'NO') AND (CONVERT(VARCHAR(10), LIS_Results.Final_Report_Date, 101) BETWEEN #ReportStartDate AND #ReportEndDate) OR (LIS_Results.Prelim_Report_Date IS NOT NULL) AND (CONVERT(VARCHAR(10), LIS_Results.Final_Report_Date, 101) BETWEEN #ReportStartDate AND #ReportEndDate)

Use an if statement in tsql to say if parameter is yes select records from table where conditions are true.
If no select records from table where conditions are true and date field is not null.

Since #PrelimOnly can only be YES or NO, use:
SELECT
...
FROM
...
WHERE #PrelimOnly = 'NO' or LIS_Results.Prelim_Report_Date is not null
...
If the parameter is NO, the left hand condition of the OR is satisfied and all rows are returned, otherwise only those non-null rows will be returned, as required.

here exist small trick:
((LIS_Results.Prelim_Report_Date <> '#PrelimOnly') OR (1=#AllowNull))
if user selected NO - set AllowNull argument to 1, other way set it to 0
NOTE: AllowNull - it is custom additional argument, you should add the same way as #PrelimOnly
another possible approach:
((LIS_Results.Prelim_Report_Date <> '#PrelimOnly') OR ('NO'='#PrelimOnly'))
for you full query you should do like this:
WHERE
(CONVERT(VARCHAR(10), LIS_Results.Final_Report_Date, 101) BETWEEN ReportStartDate AND ReportEndDate) AND
(
LIS_Results.Prelim_Report_Date is not null
or
('#PrelimOnly' = 'NO') // if instead of NO VS sends empty string replace it here
)

It was a combination of Iiya and Ian that got me the solution however the syntax was not complete and is as follows.
WHERE (#PrelimOnly = 'NO') AND (CONVERT(VARCHAR(10), LIS_Results.Final_Report_Date, 101)
BETWEEN #ReportStartDate AND #ReportEndDate) OR (LIS_Results.Prelim_Report_Date IS NOT NULL)
AND (CONVERT(VARCHAR(10), LIS_Results.Final_Report_Date, 101) BETWEEN #ReportStartDate AND
#ReportEndDate)
It requeired the Date and Time paramater to be repeated so that both paramters would still work, and the #PrelimOnly = 'NO' had to be first.

Related

AND/OR Statement in Tableau

Does anyone know how to transcribe this in Tableau:
WHERE DATE(created) = '2021-01-01'
AND (source = 'T' OR (a.promo = 'TK' AND source != 'T'))
Basically, I'm validating if source equals to "T" and grabbing all those results, but sometimes a promo but does not get flagged under the "T" source.
Is there a way to have filter that validates under this nested WHERE clause?
Thanks in advance!
If you're wanting to use a calculated field in the place of SQL then:
IF DATE([created]) = '2021-01-01'
AND ([source] = 'T' OR ([promo] = 'TK' AND [source] <> 'T'))
THEN [measure or dimension] END
That's assuming that the fields in Tableau end up being given those names.
EDIT
The calculated field above works by just ignoring data that doesn’t meet the conditions, which is very flexible — effectively pulling the condition from the WHERE clause into the SELECT clause of the query that Tableau generates.
In some other cases, you really do want to first filter to a set of data and then calculate on the resulting rows — either for performance or logic reasons.
In that case, you can define a boolean calculated field with just the condition, put it on the Filter shelf, and choose to filter to records whether the calculated field evaluates to True.
Both approaches are useful.

query multiple tables with columns based on multiple conditions

I have three columns: crew info, training info, position info. I am trying to create a report that shows the most recent date of certain trainings that each crew member has taken. Each training should have its own column but some trainings are only required for certain positions.
I have tried a case statement statement as well as just filtering in a where statement but keep getting errors. Some of the research did says that t SQL doesn't have an if statement but some says it does.
Here is the Access code that works: Ballast Water Management:
Max(IIf([CURRENT_FLAG]=1 And [QUALIFICATION_ID] In (14800000086) And [CMC_POS_CODE_TRANSLATOR] In (1,3,6,8,12,13,15,18,20,25,32,90,91,92,94,96,98,100,102,103,230),[ISSUED_ON],IIf([CMC_POS_CODE_TRANSLATOR] Not In (1,3,6,8,12,13,15,18,20,25,32,90,91,92,94,96,98,100,102,103,230),"","0")))
What I want is to either show the latest date that a crew member completed the training (if required), a blank if it's not required for them, or a 0 if it's required and they don't have it.
Okay, one of the problems you have is that you are essentially returning three data types:
a date (possibly even a datetime);
a BIT (0/1);
an empty string (VARCHAR).
So you need some way to handle all three. I assumed that you would want:
a date in YYYYMMDD format as a string;
the 0 is a string of "0";
the empty string is already a string.
So your query becomes this:
SELECT
MAX(
CASE
WHEN [CURRENT_FLAG] = 1
AND [QUALIFICATION_ID] = 14800000086
AND [CMC_POS_CODE_TRANSLATOR] IN (1,3,6,8,12,13,15,18,20,25,32,90,91,92,94,96,98,100,102,103,230)
THEN CONVERT(VARCHAR(8), [ISSUED_ON], 112)
ELSE
CASE
WHEN [CMC_POS_CODE_TRANSLATOR] NOT IN (1,3,6,8,12,13,15,18,20,25,32,90,91,92,94,96,98,100,102,103,230)
THEN ''
ELSE '0'
END
END)
FROM
MY_TABLE;
If this doesn't work what might help is showing us what you tried, and the actual error you got?
Also, TSQL does indeed allow use of IF statements, but not inside a SELECT query. So you could do this:
IF #my_dog_has_no_nose = 1
BEGIN
SELECT 'how does he smell?' AS question;
ELSE
SELECT NULL AS question;
END;
But in a SELECT statement you will have to use CASE to allow redirection.

Tableau isNull then 0 calculated field

I have my tableau workbook and I'm currently counting by a field called ID - COUNT([Id]) - while this is great, on days with no activity my dashboard doesn't show ANYTHING and I want it to show zero if there was no activity - so I do I change this to count but also replace null with 0 (zero)?
First make sure you understand what Count([ID]) does. It returns the number records in the data source that have a non-null value in the column [ID].
Count() never evaluates to null. But if you have no rows at all in your data after filtering, then you'll get an empty result set -- i.e. view data will not have any summary data to show at all - whether null or zero.
Wrapping COUNT() in a call to ISNULL() or ZN() won't help in that case.
The solution is to make sure you have at least one data row per day, even if all other fields besides the date are null. Aggregation functions ignore nulls so padding your data like this should not disturb your results. The simplest way is to make a calendar table that has one row per day with nulls in most columns. Then use a Union to combine the calendar with your original data source. Then Count(ID) will return zero on days where there are no other records besides the calendar entry.
You can also get similar results using data blending, although with a bit more complexity.

Crystal Reports Record Section not returning same data as sql

I found a solution that another Tech had posted:
New Formula:
{Product.Size} <> “xsm” or IsNull({Product.Size})
Unfortunately, when preview your report, you will find that this doesn’t work. That is not because of a mistake in our logic but rather, what I consider to be a bug in Crystal Reports. If I took this exact same condition and applied it to the database records using a query analyzer or querying tool, I would see the blank records. Unfortunately, Crystal is not allowing the null values to come through even though our formula says that they should.
The trick to circumventing this bug is to put the IsNull() check FIRST in the formula.
Thus, if we rearrange the condition to this:
IsNull({Product.Size}) or {Product.Size} <> "xsm"
WORKED LIKE A CHARM
Problem is, if I select criteria for the second OR statement ({HiredRate.UTRANSDOC}startswith{?TransYN}) and NO for the first ({HiredRate.UTRANSWEB}startswith{?WebYN}) I get only one record that meets the TransYN criteria. If I switch places in the formula putting ({HiredRate.UTRANSDOC}startswith{?TransYN}) 1st I get all of the data.
When I run the SQL query I get all of the data no matter what order they are in. The Crystal Preview only gives me all of the data on the first from the OR section.
The only thing that stands out looking at the data from SQL is that the one record Crystal is returning has YES in the Transdoc field and the Transweb field is blank. All other records show YES for Transdoc and NULL for the Transweb field.
Here is the Crystal Record Selection Formula
{HiredRate.CONTSUPREF} startswith {?LanguageCombo}
and {HiredRate.ONDATE} = {?ProjectDate}
and {HiredRate.ACTVCODE}= "SIG"
and {HiredRate.RESULTCODE} = "CLM"
and (
{HiredRate.UTRANSWEB}startswith{?WebYN}
or {HiredRate.UTRANSDOC}startswith{?TransYN}
or {HiredRate.UTRANLANL0}startswith{?LanloYN}
or {HiredRate.UINTCONSEC}startswith{?InterpYN}
or {HiredRate.UINTCONF}startswith{?IntConfYN}
or {HiredRate.UINTOPI}startswith{?OPIYN}
)
Here is the SQL query Crystal is using:
SELECT HiredRate.DEAR, HiredRate.CONTSUPREF, HiredRate.LASTDATE, HiredRate.CONTACT, HiredRate.USOURCLANG, HiredRate.UTARGLANG, HiredRate.UTRANSDOC, HiredRate.UTRANSWEB, HiredRate.UTRANLANL0, HiredRate.UINTCONSEC, HiredRate.UINTCONF, HiredRate.UINTOPI, HiredRate.ONDATE, HiredRate.ACTVCODE, HiredRate.RESULTCODE
FROM GoldMine_Main.dbo.HiredRate HiredRate
WHERE HiredRate.CONTSUPREF LIKE 'ENG>SPA%' AND (HiredRate.ONDATE>={ts '2012-04-01 00:00:00'} AND HiredRate.ONDATE<{ts '2013-04-06 00:00:00'}) AND HiredRate.ACTVCODE='SIG' AND HiredRate.RESULTCODE='CLM' AND (HiredRate.UTRANSWEB LIKE 'NO%' OR HiredRate.UTRANSDOC LIKE 'YES%' OR HiredRate.UTRANLANL0 LIKE 'NO%' OR HiredRate.UINTCONSEC LIKE 'NO%' OR HiredRate.UINTCONF LIKE 'NO%' OR HiredRate.UINTOPI LIKE 'NO%')
ORDER BY HiredRate.DEAR, HiredRate.CONTACT
This is happening because the {HiredRate.UTRANSWEB} is null - the rest of the expression is therefore evaluating as null in Crystal, even though (logically) it shouldn't.
When the first two or conditions are swapped around, the {HiredRate.UTRANSDOC} condition evaluates as true and the rest of the expression is short-circuited - which is why records are then selected.

SSRS report parameters

In my SSRS report there are 2 parameters called DataSourceIDList and ReporterIDlist.
DataSourceIDList : is a drop down list and this will populate based on SQL query.
ReporterIDlist : is a drop down list and this will populate reporters based on selected Datasourceid from DataSourceIDList and this is also a SQL query.
both parameters are optional fields but when i am running the report i am getting error called "Please select value for DataSourceID" but i set the property for that parameter as allow NULL values
and same problem for ReporterIDlist also.
Please suggest your suggestion....
Thanks in advance...
I think that SSRS will not allow you NULL value if parameter have datasource.
Trick that I do when I need all values that is: I change data source for parameters that is in list have
null, or ( 0) value, and option select ALL, and after that I set default value to null so users do not have to touch parameters before it call it
Something like this,
Select 1,null as ValueOfParam,'All values' as TextOfParam
union all
select 2,id,name from myDatasourceThatHaveParamValues
order by 1,name
to verify date, you can use this method too:
make two rectangle; insert table/matrix in first rectangle
in second rectangle insert msg like
"Selected Date is not valid, please select correct date"
or "Start Date should be less less than End Date"
put appropriate msg, and make condition in 1st rectangle where all tables/matrix is there
iif( Parameters!StartDate.Value < Parameters!EndDate.Value,false,true)
in second rectangle where Error msg is inserted write this:
iif( Parameters!StartDate.Value < Parameters!EndDate.Value,true,false)