sql statement conditions - asp.net

I want to select all the Female patients from the patient table where the area = south or area= west and then group the result by Disease name
So I had to write the where condition like this :
command10.CommandText = "SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO FROM PatientAffectDisease D INNER JOIN patient P on D.Patient_ID = P.Patient_ID WHERE P.Gender='" & "female" & "'" & " AND P.Area='" & "south" & " '" & "OR P.Area='" & "west" & " '" & " GROUP BY DiseaseName "
But this doesn't return the right result.
Any Idea?

Put parenthesis around your OR'd conditions
e.g.
WHERE P.Gender='" & "female" & "'" & " AND
(P.Area='" & "south" & " '" & "OR P.Area='" & "west" & " '" & ")
or just use an IN clause ...
where p.gender = 'female' and p.area in ('south', 'west')

The issue is that you had extra spaces after south and west with this code: " '"
You were trying to find 'south ' or 'west ', not 'south' or 'west'.
You can also modify this condition to use an IN clause.
command10.CommandText = "SELECT D.DiseaseName, COUNT(1) AS PNO FROM PatientAffectDisease D INNER JOIN patient P on D.Patient_ID = P.Patient_ID WHERE P.Gender='female' AND P.Area IN ('south', 'west') GROUP BY DiseaseName"

I think the problem is in your where clause specifically related to not using parentheses.
command10.CommandText =
"SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO " & _
" FROM PatientAffectDisease D " & _
" INNER JOIN patient P on D.Patient_ID = P.Patient_ID " & _
" WHERE P.Gender='female' AND P.Area in ('south','west') " _
" GROUP BY DiseaseName "

Here is the text of your query:
SELECT
D.DiseaseName,
COUNT(D.Patient_ID) AS PNO
FROM PatientAffectDisease D
INNER JOIN patient P on D.Patient_ID = P.Patient_ID
WHERE P.Gender='female'
AND P.Area='south '
OR P.Area='west '
GROUP BY DiseaseName
In SQL, the AND naturally has precendence over the OR.
So you're effectively asking
WHERE (P.Gender='female' AND P.Area='south') OR (p.Area = 'west' )
You must use brackets to explicitly state the precedence you need
WHERE P.Gender='female' AND (P.Area='south' OR p.Area='west')

The reason your posted query isn't working properly is because you have an extra space after 'west' and 'south' in the generated query.
You should always group your logic with () to make it easier to maintain and understand the code - and keep away from bugs such as this one.
AND binds harder than OR, so what you had earlier was the same as writing:
(P.Gender = 'female' AND P.Area = 'west') OR P.Area = 'south' -- not correct
Instead of using P.Area = 'west' OR P.Area = 'south' you can use the IN operator, as in the below example:
SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO
FROM PatientAffectDisease D
INNER JOIN patient P ON D.Patient_ID = P.Patient_ID
WHERE P.Gender = 'female' AND P.Area IN ('west','south')
GROUP BY D.DiseaseName
command10.CommandText = "SELECT D.DiseaseName, COUNT(D.Patient_ID) AS PNO FROM PatientAffectDisease D INNER JOIN patient P ON D.Patient_ID = P.Patient_ID WHERE P.Gender = 'female' AND P.Area IN ('west','south') GROUP BY D.DiseaseName"

Related

DAX formula to show not repeated values and count them

I have a table with for which the column "CODE" has values like this:
FTRA2
BRB92
RBRB4
XYZ
SXM4
RBRB4
NLDR
XYZ
FTRA2
POEU
FTRA2
I currently have this formula
="[ Unique values " & DISTINCTCOUNT(MyTable[CODE]) & "]
" & CONCATENATEX(DISTINCT(MyTable[CODE]), MyTable[CODE] ,", ")
that outputs this:
[ Unique values 7 ]
FTRA2, BRB92, RBRB4, XYZ, SXM4, NLDR, POEU
I would like to show all the unique values and their count (except those with the string "XYZ") and below show how many "XYZ" values are, like this:
[ Unique values 6 ]
FTRA2, BRB92, RBRB4, SXM4, NLDR, POEU
[2 XYZ values]
In this case there are 2 "XYZ" values, but could be zero XYZ values too.
I'm using Excel 2016.
How can I do this? Thanks in advance.
UPDATE1
I get this error tryng Joe's solution.
UPDATE2
Joe, I was able to make work your first part modifying like this:
= VAR ExcludeValue = "XYZ"
RETURN
CALCULATE(
"[ Unique values " & DISTINCTCOUNT(MyTable[Code]) & " ]"
" & CONCATENATEX(DISTINCT(MyTable[Code]), [Code], ", ")
, MyTable[Code] <> ExcludeValue
)
But when I add the second part it says this error
This formula is invalid or incomplete: 'Calculation error in
measure 'MyTable[Code]: The function COUNT takes an argument
that evaluates to numbers or dates and cannot work with values
of type String.'.
I also removed the UNICHAR since doesn't work on Excel.
UPDATE3
Joe's solution it works correctly after I modified the COUNT(MyTable[Code]) to COUNTROWS(MyTable)
The final solution looks like this.
=VAR ExcludeValue = "XYZ"
RETURN
CALCULATE(
"
[ Unique values " & DISTINCTCOUNT(MyTable[Code]) & " ]
" & CONCATENATEX(DISTINCT(MyTable[Code]), [Code], ", ")
, MyTable[Code] <> ExcludeValue
) & "
" & CALCULATE(
"[" & COUNTROWS(MyTable) & " " & ExcludeValue & " values]"
, MyTable[Code] = ExcludeValue
) & "
"
Update4
Print nothing when there is no "XYZ" values works with your IF() addition. I've tried to follow your logic to do the same when there is no values at all. I added an
IF() to count if MyTable[Code] <> ExcludeValue is greater than 0 and if true do original CALCULATE, if not BLANK() but doesnt work.
CountLabel =
VAR ExcludeValue = "XYZ"
RETURN
IF(
CALCULATE(COUNTROWS(MyTable), MyTable[Code] <> ExcludeValue) > 0,
CALCULATE(
"[ Unique values " & DISTINCTCOUNT(MyTable[Code]) & " ]"
& UNICHAR(10) &
CONCATENATEX(DISTINCT(MyTable[Code]), [Code], ", ")
, MyTable[Code] <> ExcludeValue
),
BLANK()
)
& IF(
CALCULATE(COUNTROWS(MyTable), MyTable[Code] = ExcludeValue) > 0,
UNICHAR(10) & " " & UNICHAR(10) &
CALCULATE(
"[" & COUNTROWS(MyTable) & " " & ExcludeValue & " values]"
, MyTable[Code] = ExcludeValue
),
BLANK()
)
FINAL UPDATE
This is the final formula that works as expected. Thanks to Joe's help in this case.
=VAR ExcludeValue = "XYZ"
RETURN
IF(
CALCULATE(DISTINCTCOUNT(MyTable[Code]), MyTable[Code] <> ExcludeValue) > 0 &&
MyTable[Count of Code]>0,
CALCULATE(
"
[ Unique values " & DISTINCTCOUNT(MyTable[Code]) & " ]
" & CONCATENATEX(DISTINCT(MyTable[Code]), [Code], ", ")
, MyTable[Code] <> ExcludeValue
),
BLANK()
)
&
IF(
CALCULATE(DISTINCTCOUNT(MyTable[Code]), MyTable[Code] <> ExcludeValue) > 0 &&
CALCULATE(COUNTROWS(MyTable), MyTable[Code] = ExcludeValue) > 0,
"
" &
BLANK()
)
& IF(
CALCULATE(COUNTROWS(MyTable), MyTable[Code] = ExcludeValue) > 0,
CALCULATE(
"[" & COUNTROWS(MyTable) & " " & ExcludeValue & " values]"
, MyTable[Code] = ExcludeValue
),
BLANK()
) & "
"
UPDATE: - Changed my formula from using COUNT to COUNTROWS based on feedback from OP.
UPDATE 2: - Add IF statement to formula to exclude excluded count when 0.
UPDATE 3: - Add IF statement to formula to exclude distinct count when 0.
I will say that I created this solution in Power BI, but Excel 2016 should have the same functionality when it comes to DAX (with minor tweaks).
I created a measure with your formula, and simply wrapped each piece (the distinct count, and the repeated count) with a CALCULATE statement that is used to filter your MyTable down to the codes you care about.
I used a variable for the "XYZ" value in case that needs to be changed. Now you can simply change it in one place (at the beginning of the formula) and the rest of the formula will reflect that change.
I also used UNICHAR(10) to add the line breaks instead of counting on the new lines in the formula.
With the IF statements...
The first will check if the distinct count of items not equal to the specified value is greater than zero. If not, it won't show anything.
The second will check if the distinct count and the row count of the specified value are both greater than zero. If they are, it will add the line break.
The third will check if the row count of items equal to the specified value is greater than zero. If not, it won't show anything.
The final formula is:
CountLabel =
VAR ExcludeValue = "XYZ"
RETURN
IF(
CALCULATE(DISTINCTCOUNT(MyTable[Code]), MyTable[Code] <> ExcludeValue) > 0,
CALCULATE(
"[ Unique values " & DISTINCTCOUNT(MyTable[Code]) & " ]"
& UNICHAR(10) &
CONCATENATEX(DISTINCT(MyTable[Code]), [Code], ", ")
, MyTable[Code] <> ExcludeValue
),
BLANK()
)
&
IF(
CALCULATE(DISTINCTCOUNT(MyTable[Code]), MyTable[Code] <> ExcludeValue) > 0 &&
CALCULATE(COUNTROWS(MyTable), MyTable[Code] = ExcludeValue) > 0,
UNICHAR(10) & " " & UNICHAR(10),
BLANK()
)
& IF(
CALCULATE(COUNTROWS(MyTable), MyTable[Code] = ExcludeValue) > 0,
CALCULATE(
"[" & COUNTROWS(MyTable) & " " & ExcludeValue & " values]"
, MyTable[Code] = ExcludeValue
),
BLANK()
)
Here is what the result looks like (again, in Power BI).
Came up with something similar but slightly different using COUNTROWS instead of CALCULATE to filter the table for the unique item. Also I am just learning DAX so don't know if this is a "proper" way to do it, but it seems to work.
Measure =
VAR Exclusion = "XYZ"
RETURN
"[ Unique values " & COUNTROWS(FILTER(DISTINCT(MyTable[CODE]), [CODE] <> Exclusion)) & "]
" & CONCATENATEX(FILTER(DISTINCT(MyTable[CODE]), [CODE] <> Exclusion), [CODE] ,", ") &
"
[" & COUNTROWS(FILTER(MyTable, MyTable[CODE] = Exclusion))+0 & " " & Exclusion & " values]"

SSRS - CASE Expression with Parameter in SELECT

I have a report in Report Builder, SSRS. I need to add a CASE with Parameter in the SELECT Statement (PL/SQL).
The parameters are: #DateFrom, #DateTo, #Check.
If I hardcode the value (without parameter values) the my query is fine.
But if I code like the below I got error 'End of Statement expected'.
SELECT
....,
CASE
WHEN ( (ExpiryDate BETWEEN '" & UCase(Format(Parameters!DateFrom.Value,"dd-MMM-yyyy")) &"'
AND '" & UCase(Format(Parameters!DateTo.Value,"dd-MMM-yyyy")) &"'
)
AND Check IN ('" & Join(Parameters!Check.Value,"','") & "')
) THEN 'Current'
WHEN ((ExpiryDate <= '" & UCase(Format(Parameters!DateFrom.Value,"dd-MMM-yyyy")) & "') AND Check = 'Y') THEN 'Before'
WHEN ((ExpiryDate >= '" & UCase(Format(Parameters!DateTo.Value,"dd-MMM-yyyy")) & "') AND Check = 'Y') THEN 'After'
END as MyGroup,
...
FROM ...

Summary type Sum is not appropriate for column of type System.String error

I am getting this error whenever I try to run my project although the column isn't of type system.string. I have a page that is coded the same way with different numbers and it doesn't give me this error. This is my SQL string:
MyCompSqlString = "SELECT (KAIPRDDTA.F4102LA.IBPRP6)ColOne, (KAIPRDCOM.F0005.DRDL01)ColTwo, COUNT(KAIPRDDTA.F42119LA.SDSOQS*.01)ColThree, SUM(KAIPRDDTA.F42119LA.SDAEXP*.01*CXCRR)ColFour, count(SDDOC)ColFive, SUM(KAIPRDDTA.F42119LA.SDSOQS*.01)ColSix "
MyCompSqlString += "FROM KAIPRDDTA.F42119LA, KAIPRDDTA.F55311, KAIPRDCOM.F0005, KAIPRDDTA.F0015, KAIPRDDTA.F4102LA"
MyCompSqlString += "WHERE DRSY = '41' AND DRRT = '01' AND TRIM(DRKY) = IBPRP6 AND KAIPRDDTA.F42119LA.SDITM = KAIPRDDTA.F4102LA.IBITM AND KAIPRDDTA.F42119LA.SDMCU = KAIPRDDTA.F4102LA.IBMCU AND KAIPRDDTA.F42119LA.SDSLSM = KAIPRDDTA.F55311.TERR AND (KAIPRDDTA.F42119LA.SDIVD >= " & SDJ & ") AND (KAIPRDDTA.F42119LA.SDIVD <= " & EDJ & ") AND "
MyCompSqlString += "(KAIPRDDTA.F42119LA.SDSLSM > 0) AND (KAIPRDDTA.F42119LA.SDGLC NOT IN ('FT60', 'TXTX', 'IN20', 'INSP', 'INWC', 'INWR', 'INWS','',' ')) AND "
MyCompSqlString += "(trim(KAIPRDDTA.F42119LA.SDLNTY) NOT IN ('T', 'F', 'TX', 'TA', 'TS', 'RF', 'RP','BC')) AND (KAIPRDDTA.F42119LA.SDNXTR <> '999') AND (KAIPRDDTA.F42119LA.SDDCTO not in ('ST','CR','SR')) "
MyCompSqlString += "AND (KAIPRDDTA.F55311.VIEWID = '" & MyView & "') AND (SDAN8 <> 24157 and SDAN8 <> 152) AND ((SDTRDJ-1)=CXEFT) AND (SDBCRC=CXCRCD) AND (CXCRDC ='USD')"
MyCompSqlString += "GROUP BY KAIPRDDTA.F4102LA.IBPRP6, KAIPRDCOM.F0005.DRDL01"
and this is my summary row:
<ig:SummaryRow EmptyFooterText="" FormatString=" {1}" ShowSummariesButtons="false">
<ColumnSummaries>
<ig:ColumnSummaryInfo ColumnKey="ColThree">
<Summaries>
<ig:Summary SummaryType="Sum" />
</Summaries>
</ig:ColumnSummaryInfo>
<ig:ColumnSummaryInfo ColumnKey="ColFour">
<Summaries>
<ig:Summary SummaryType="Sum" />
</Summaries>
</ig:ColumnSummaryInfo>
<ig:ColumnSummaryInfo ColumnKey="ColFive">
<Summaries>
<ig:Summary CustomSummaryName="100.00%" />
</Summaries>
</ig:ColumnSummaryInfo>
<ig:ColumnSummaryInfo ColumnKey="ColTwo">
<Summaries>
<ig:Summary CustomSummaryName="Totals:" />
</Summaries>
</ig:ColumnSummaryInfo>
</ColumnSummaries>
Does anyone have any suggestions as to why it is giving me this error? Let me know if you need any more information and I will update my question. Thanks in advance for your responses
You have a group which is NULL. This error means not all of the values are integer. So this query must produce a NULL as a value on some of the rows.

syntax error in SQL Update statement

I'm getting a syntax error in my UPDATE statement, but I'm not sure where exactly it is. Here's my code:
strSelected = "UPDATE CFRRR SET assignedby = " & Me.cmbassignedby.Column(1) & ", assignedto = " & _
Me.cmbassignedto.Column(2) & ", Dateassigned = " & Now() & ", actiondate = " & _
Now() & ", Workername = " & Me.cmbassignedto.Column(2) & ", WorkerID = " & _
Me.cmbassignedto.Column(1) & " WHERE CFRRRID In ( " & strSelected & " );"
CurrentDb.Execute strSelected
It's most likely because of the Now() function, which also prints the current time (seperated with a space) - hence the syntax error. Try to surround them with single quotation marks.
You can also print out the SQL Statement
Debug.Print strSelected to see what you have concatenated...

Make Certificate Visible to user after user meets target

I am having problem wrapping my head around this problem.
If you run the query embedded in code below, it shows Total Questions (TotalQuestions) asked, Total Correct (TotalCorrect2) and percentage correct (PercentCorrect2).
We have students who participate in video tutorials.
After each lesson, they are given quizzes, a total of 30 questions.
To pass through each segment of the tutorials, a student must score at least 80% of the quizzes.
The code below is calculating Total questions, total correct and percentage correct.
Here is where I am having issues.
If a student answers all 30 questions AND gets 80% or more of the questions correct, a certificate is exposed to the student so s/he can print his or her certificate.
If both criteria is not met, the certificate stays hidden from the student.
I am having difficulty with the IF portion of this task.
For instance,
if totalQuestions = 30 and percentCorrect2 >= 80 then
btnGetUser.Visible = True
else
btnGetUser.Visible = False
end if
This above is not working.
When I run the code, and a particular user meets the condition of the IF statement, the certificate is supposed to be exposed. It does so when I run it in SSMS.
So far, the certificate has remained hidden even though I am testing with users who have taken and passed the tests and have made the conditions.
When I debug the code, I can see that totalQuestions shows 30 which is correct but the rest show 0.
Any ideas what I could be doing wrong?
Dim s As String = ";WITH Questions AS " & _
" ( SELECT SQ.QuestionID, " & _
" CorrectChoices = COUNT(NULLIF(SC.IsCorrect, 0)), " & _
" ChoicesGiven = COUNT(SA.ChoiceID), " & _
" CorrectChoicesGiven = COUNT(CASE WHEN SA.ChoiceID IS NOT NULL AND SC.IsCorrect = 1 THEN 1 END), " & _
" ExtraChoicesGiven = CASE WHEN COUNT(SA.ChoiceID) > COUNT(NULLIF(SC.IsCorrect, 0)) THEN COUNT(SA.ChoiceID) - COUNT(NULLIF(SC.IsCorrect, 0)) ELSE 0 END " & _
" FROM SurveyQuestions SQ " & _
" INNER JOIN SurveyChoices SC " & _
" ON SQ.QuestionId = SC.QuestionID " & _
" LEFT JOIN SurveyAnswers SA " & _
" ON SA.QuestionId = SC.QuestionID " & _
" AND SA.ChoiceID = SC.ChoiceID " & _
" AND SA.UserName = #username " & _
" GROUP BY SQ.QuestionID " & _
" ), QuestionScores AS " & _
" (SELECT QuestionID, " & _
" Score = CASE WHEN CorrectChoicesGiven - ExtraChoicesGiven < 0 THEN 0 " & _
" ELSE CAST(CorrectChoicesGiven - ExtraChoicesGiven AS FLOAT) / CorrectChoices " & _
" END, " & _
" Score2 = ISNULL(CAST(CorrectChoicesGiven AS FLOAT) / NULLIF(CASE WHEN ChoicesGiven > CorrectChoices THEN ChoicesGiven ELSE CorrectChoices END, 0), 0) " & _
" FROM Questions " & _
" )
" SELECT TotalQuestions = COUNT(*), " & _
" TotalCorrect = SUM(Score), " & _
" PercentCorrect = CAST(100.0 * SUM(Score) / COUNT(*) AS DECIMAL(5, 2)), " & _
" TotalCorrect2 = SUM(Score2), " & _
" PercentCorrect2 = CAST(100.0 * SUM(Score2) / COUNT(*) AS DECIMAL(5, 2)) " & _
" FROM QuestionScores;"
Dim connStr As String = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim conn As New SqlConnection(connStr)
Dim cmd As New SqlCommand(s, conn)
Dim TotalQuestions As Integer
Dim TotalCorrect As Double
Dim TotalPercent As Decimal
Dim TotalCorrect2 As Double
Dim TotalPercent2 As Decimal
conn.Open()
cmd.Parameters.AddWithValue("#username", username.Text)
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
TotalQuestions = reader.GetInt32(0)
TotalCorrect = reader.GetDouble(1)
TotalPercent = reader.GetDecimal(2)
TotalCorrect2 = reader.GetDouble(3)
TotalPercent2 = reader.GetDecimal(4)
End If
reader.Close()
conn.Close()
If TotalQuestions = 30 and TotalPercent2 >= 80 Then
btnGetUser.Visible = True
Else
btnGetUser.Visible = False
End If

Resources