How to make a case condition inside codeigniter query - sql

I have some query like this :
$this->db->query("SELECT `no_request`,`date_in`,`location`,`d_point`,`username`,SUM(request.`persen`) AS 'Persen',
CASE
WHEN SUM(Persen) = 0 THEN 'Pending'
WHEN SUM(persen) = 100 THEN 'Complete'
WHEN SUM(persen) > 0 AND SUM(persen) < 100 THEN 'On Process'
END AS 'states'
FROM request WHERE `location` = '$lokasi' GROUP BY `no_request`
HAVING
CASE
WHEN `Persen` = 0 THEN `states` = 'Pending'
END", TRUE)->result_array();
I want make query original from codeigniter but i have some problem with my query :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen);
$this->db->select("
CASE
WHEN SUM('persen') = 0 THEN 'Pending'
WHEN SUM('persen') = 100 THEN 'Complete'
WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
END", FALSE);
$this->db->from($this->table);
$this->db->where($this->location . ' = ' . $location);
$this->db->group_by($this->group);
$result = $this->db->get();
Is my query is wrong?, or I can't use case inside $this->db->select()

$this->db->select() acknowledges a discretionary second parameter. In the event that you set it to FALSE, CodeIgniter won't attempt to ensure your field or table names. This is helpful on the off chance that you need a compound select explanation where programmed getting away of fields may break them.
for reference:- https://codeigniter.com/userguide3/database/query_builder.html#selecting-data

I have make a some fault in my query to make my query isn't working, but now is code is fine and I already done with my code, I change my query like this :
From this code :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen);
$this->db->select("
CASE
WHEN SUM('persen') = 0 THEN 'Pending'
WHEN SUM('persen') = 100 THEN 'Complete'
WHEN SUM('persen') > 0 SUM('persen') < 100 THEN 'On Process'
END", FALSE);
$this->db->from($this->table);
$this->db->where($this->location . ' = ' . $location);
$this->db->group_by($this->group);
$result = $this->db->get();
Became like this :
$this->db->select($this->fetching_column);
$this->db->select_sum($this->persen, 'Persen');
$this->db->select("
CASE
WHEN SUM(Persen) = 0 THEN 'Pending'
WHEN SUM(Persen) = 100 THEN 'Complete'
WHEN SUM(Persen) > 0 AND SUM(Persen) < 100 THEN 'On Process'
END AS 'states'");
$this->db->from($this->table);
$this->db->where($this->location, $location);
$this->db->group_by($this->group);
$result = $this->db->get();

Related

Case statement with Multiple Nested Else

I have this requirement where I have to emulate an Excel formula into Oracle SQL. Since Excel is very rudimentary, everything goes in it but SQL is regimented and must fall in line.
This is the formula in Excel (Business Category):
=IF([#[Order Days]]="","",
IF(OR([#business type]="Probation Touch Point",[#business type]="Referral",
[#business type]="Mystery Shopping"),IF([#[Order Days]]>45,"Allowed","Not Allowed"),
IF(OR(AND([#business status]="Assigned",[#[Order Days]]>60),
AND([#business status]="Pre-Review",[#[Order Days]]>60),
AND([#business status]="In-Review",[#[site]]="Location",[#[Order Days]]>44),
AND([#business status]="In-Review",[#[site]]="Headquarters",[#[Order Days]]>74)),"Permitted",
IF([#business status]="Post-Review",IF([#business review]=0,IF([#[Order Days]]>44,"Allowed","Not
Allowed"),
IF(OR(AND([#[site]]="Headquarters",[#[Order Days]]>90),
AND([#[site]]="Location",[#[Order Days]]>60)),"Allowed","Not Allowed")),"Not Allowed"))))
As its conspicuous, there are multiple else within a single formula and its purposeful.
My SQL formula:
case when order_days is null then null
when business_type like '%Touch%' or business_type = 'Referral'
or business_type like 'Myster%' and order_days > 45 then 'Allowed'
when (business_status = 'Assigned' and order_days > 60) or
(business_status = 'Pre-Review' and order_days > 60) or
(business_status = 'In-Review' and site like 'Loca%' and order_days > 44) or
(business_status = 'In-Review' and site like 'Head%' and order_days > 74) then 'Permitted'
when (business_status like 'Post%' or business_type = 0 or order_days > 44) then 'Allowed'
when (site like 'Head%' and order_days > 90) then 'Allowed'
when (site like 'Loca%' and order_days > 60) then 'Allowed' else 'Not Allowed'
end as business_category
The sql case is futile because it results in wrongful figures.
Excel result:
Business Category Count of Rows
Allowed 130
Not Allowed 1122
Permitted 200
SQL Result:
business_category Count
Allowed 980
Not Allowed 272
Permitted 200
Can someone please provide assistance!
You switched the logic to use LIKE in some places. Because you didn't include any data it's impossible to determine if this was causing some of the problems you reported, but I've restored the comparison to the individual values used in the Excel formula. In addition, I think your interpretation of the "business_review <> 0" and the "business_status <> 'Post Review'" branches may have been in error.
The following should do what you want:
case
when order_days is null
then null
when business_type in ('Probation Touch Point', 'Referral', 'Mystery Shopping') AND order_days > 45
then 'Allowed'
when (business_status = 'Assigned' and order_days > 60) or
(business_status = 'Pre-Review' and order_days > 60) or
(business_status = 'In-Review' and site = 'Location' and order_days > 44) or
(business_status = 'In-Review' and site = 'Headquarters' and order_days > 74) then 'Permitted'
when (business_status = 'Post-Review' and business_review = 0 and order_days > 44) then 'Allowed'
when (business_status = 'Post-Review' and business_review = 0 and order_days <= 44) then 'Not Allowed'
when (business_status = 'Post-Review' and business_review <> 0 and ((site = 'Headquarters' and order_days > 90) or
(site = 'Location' and order_days > 60))
then 'Allowed'
else 'Not Allowed'
when business_status <> 'Post-Review' then 'Not Allowed'
end as business_category
In future you might want to post test data - CREATE TABLE statement(s) and INSERT statements to put data into those table(s) are a good idea - along with expected results.

Converting VB conditions to SQL conditions

There are some VB conditions that I need to execute in SQL query. Is this possible? Here's the code:::::::::::::::::::::::::::::::::::::::::::::::
If (ds.Tables(0).Rows.Count > 0) Then
Dim timeIn = ds.Tables(0).Rows(0)("TimeIn").ToString
Dim timeOut = ds.Tables(0).Rows(0)("TimeOut").ToString
If Not String.IsNullOrEmpty(timeIn) And Not String.IsNullOrEmpty(timeOut) Then
Dim result = DateTime.Compare(Convert.ToDateTime(timeIn), Convert.ToDateTime(timeOut))
If result > 0 Then 'last timeIn later than last timeOut
attendanceStatus = "On"
Else
attendanceStatus = "Off"
End If
ElseIf Not String.IsNullOrEmpty(timeIn) And String.IsNullOrEmpty(timeOut) Then
attendanceStatus = "On"
End If
lblAttendStatus.Text = attendanceStatus
End If
End If
You can do that by including in your SQL statement after SELECT:
CASE WHEN TimeIn < TimeOut THEN 'Off' ELSE 'On' END AS attendanceStatus,

VBA Select Case runs through without selection

I am really puzzled by this one. Searched the net already but did not find any answer related to my specific case. I have the following code:
Dim CE_res As Integer
For Index = 1 To 7
Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)
If CE_res = 0 Then
' Everything ok
Status = "Pass"
Else
Select Case CE_res
Case CE_res < -1500
Status = "Invalid kV Value"
Case CE_res < -999
Status = "No kV Value"
Case CE_res < -399
Status = "kV too high"
Case CE_res = 0
Status = "kV too low"
Case CE_res > 500
Status = "Invalid mAs Value"
Case CE_res > 49
Status = "mAs Value missing"
Case CE_res > 9 And CE_res < 50
Status = "Adapt Target"
Case CE_res > 200
Status = "Adapt Filter"
Case Else
Status = "No Selection"
End Select
End If
The CE_res is set to 50. However, always Case Else is selected. Declared CE_res as integer, coverted Worksheets("werkblad").Range("CEres" & Index).Value to an integer, just to be sure.
However, it does not seem to execute the Select Case correctly. Tried it also with other values, even changed the case CE_res > 49 to CE_res = "50" but this also did not work.
Now, I am out of ideas what could be wrong.
You are not using the correct syntax for the Case statements
Dim CE_res As Integer
For Index = 1 To 7
Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)
If CE_res = 0 Then
' Everything ok
Status = "Pass"
Else
Select Case CE_res
Case < -1500
Status = "Invalid kV Value"
Case < -999
Status = "No kV Value"
Case < -399
Status = "kV too high"
Case 0 ' or possibly Case < 0 ????
Status = "kV too low"
Case > 500
Status = "Invalid mAs Value"
Case > 200
Status = "Adapt Filter"
Case > 49
Status = "mAs Value missing"
Case > 9
Status = "Adapt Target"
Case Else
Status = "No Selection"
End Select
End If
Note that I had to move > 200 prior to > 49, otherwise a value of, for instance, 230 would have matched > 49 and therefore never reached your > 200.
The way you had it, the statement Case CE_res < -1500 would test if CE_res was < -1500. If it was, that would return a True which was then compared to the object of the case statement (i.e. CE_res) and, if it matched (which it wouldn't) that leg of the Select statement would execute.
As mentioned by other members, due to your use of < > = comparitors you need to make sure you order them correctly or they will not work as intended. With the very specific values you are using you would probably be better to use TO and be more specific with the values.
Select Case
Case -1000 TO -1500
'Do This
Case -400 TO -999
'Do That
Case -1 TO -399
'Do Something Else
End Select
If you do this the there is no ambiguity as to what does what, it's easier to read and the operation order doesn't matter.
You also don't need to add the CE_res to each Case statement as you already specified the variable on the Select Case CE-res line. The Correct syntax is
Select Case CE_res
Case <-1500
Status = "Invalid kV Value"
End Select

CASE in WHERE clause with array

In my program the user has 4 options, "ALL","FK","FK2","FK3". The below code does not work because of the Array.
WHERE
JOBOP.CC_CODE in
CASE :P4_MACHINES
WHEN 'ALL' THEN ('FK','FK2','FK3')
ELSE :P4_MACHINES
END
Can someone help me form this clause properly or tell me if it is not possible please?
Just to reiterate my goal in other terms,
IF :P4_MACHINES = 'ALL' THEN
JOBOP.CC_CODE in ('FK','FK2','FK3')
ELSE
JOBOP.CC_CODE = P4_MACHINES
END
Based on your question update, you can try this:
where ( (:P4_MACHINES = 'ALL' AND JOBOP.CC_CODE in ('FK','FK2','FK3'))
OR JOBOP.CC_CODE = :P4_MACHINES )
I may be missing a few brackets since I do not have the entire query.
Hmmm . . . Is this what you want?
where (:P4_MACHINES = 'ALL' and JOBOP.CC_CODE in ('FK','FK2','FK3'))
or (JOBOP.CC_CODE = :P4_MACHINES)
WHERE 1 = CASE
WHEN :P4_MACHINES = 'ALL' THEN CASE WHEN JOBOP.CC_CODE IN ('FK','FK2','FK3') THEN 1 ELSE 0 END
ELSE CASE WHEN JOBOP.CC_CODE = :P4_MACHINES THEN 1 ELSE 0 END
END

Query Timeout Expired in SSAS Cube Processing

While migrating a cube from 2008 to 2014, we had a cube processing failure with the message "Query Timeout Expired : HYT00". I looked into the error information and found a certain query executing for more than an hour which is causing the issue. The query is,
SELECT [dbo_IndicatorFact].[PY] AS [dbo_IndicatorFactPY0_0],[dbo_IndicatorFact].[BP] AS [dbo_IndicatorFactBP0_1],[dbo_IndicatorFact].[RE] AS [dbo_IndicatorFactRE0_2],[dbo_IndicatorFact].[UCPY] AS [dbo_IndicatorFactUCPY0_3],[dbo_IndicatorFact].[UCBP] AS [dbo_IndicatorFactUCBP0_4],[dbo_IndicatorFact].[UCRE] AS [dbo_IndicatorFactUCRE0_5],[dbo_IndicatorFact].[GRPY] AS [dbo_IndicatorFactGRPY0_6],[dbo_IndicatorFact].[GRBP] AS [dbo_IndicatorFactGRBP0_7],[dbo_IndicatorFact].[GRRE] AS [dbo_IndicatorFactGRRE0_8],[dbo_IndicatorFact].[NRPY] AS [dbo_IndicatorFactNRPY0_9],[dbo_IndicatorFact].[NRBP] AS [dbo_IndicatorFactNRBP0_10],[dbo_IndicatorFact].[NRRE] AS [dbo_IndicatorFactNRRE0_11],[dbo_IndicatorFact].[GRC2] AS [dbo_IndicatorFactGRC20_12],[dbo_IndicatorFact].[AnalysisCategoryId] AS [dbo_IndicatorFactAnalysisCategoryId0_13],[dbo_IndicatorFact].[IndicatorTypeId] AS [dbo_IndicatorFactIndicatorTypeId0_14],[dbo_IndicatorFact].[IndicatorNameId] AS [dbo_IndicatorFactIndicatorNameId0_15],[dbo_IndicatorFact].[CategoryId] AS [dbo_IndicatorFactCategoryId0_16],[dbo_IndicatorFact].[CountryId] AS [dbo_IndicatorFactCountryId0_17],[dbo_IndicatorFact].[FiscalQuarterId] AS [dbo_IndicatorFactFiscalQuarterId0_18]
FROM
(
SELECT vwIndicatorFact.IndicatorId AS Id,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE vwIndicatorFact.PY END END AS PY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE vwIndicatorFact.BP END END AS BP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN vwIndicatorFact.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE vwIndicatorFact.RE END END AS RE,
vwIndicatorFact.BPvsPY, vwIndicatorFact.BPvsPYpercent, vwIndicatorFact.REvsBP, vwIndicatorFact.REvsBPpercent, vwIndicatorFact.REvsPY,
vwIndicatorFact.REvsPYpercent,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.PY END ELSE CASE IndicatorFact_GRC2.PY
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.PY END END END AS UCPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.BP END ELSE CASE IndicatorFact_GRC2.BP
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.BP END END END AS UCBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.RE END ELSE CASE IndicatorFact_GRC2.RE
WHEN 0 THEN 0 ELSE CASE vwIndicatorFact.IndicatorNameId WHEN 1 THEN 1000000 ELSE IndicatorFact_UC.RE END END END AS UCRE, vwIndicatorFact.IndicatorNameId,
vwIndicatorFact.CategoryId, vwIndicatorFact.AnalysisCategoryId, vwIndicatorFact.CountryId, vwIndicatorFact.FiscalQuarterId, vwIndicatorFact.IndicatorTypeId,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE IndicatorFact_GR.PY END END AS GRPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE IndicatorFact_GR.BP END END AS GRBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_GR.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE IndicatorFact_GR.RE END END AS GRRE,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.PY ELSE CASE IndicatorFact_GRC2.PY WHEN 0 THEN 0 ELSE IndicatorFact_NR.PY END END AS NRPY,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.BP ELSE CASE IndicatorFact_GRC2.BP WHEN 0 THEN 0 ELSE IndicatorFact_NR.BP END END AS NRBP,
CASE vwIndicatorFact.IndicatorTypeId WHEN 1 THEN IndicatorFact_NR.RE ELSE CASE IndicatorFact_GRC2.RE WHEN 0 THEN 0 ELSE IndicatorFact_NR.RE END END AS NRRE,
IndicatorFact_GRC2.BP AS GRC2
FROM
dbo.vwIndicatorFact INNER JOIN
dbo.vwIndicatorFact AS IndicatorFact_UC ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_UC.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_UC.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_UC.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_UC.CategoryId AND IndicatorFact_UC.IndicatorNameId = 1 LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_GR ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_GR.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_GR.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_GR.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_GR.CategoryId AND IndicatorFact_GR.IndicatorNameId = 3 AND
IndicatorFact_GR.AnalysisCategoryId = vwIndicatorFact.AnalysisCategoryId LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_NR ON vwIndicatorFact.IndicatorTypeId = IndicatorFact_NR.IndicatorTypeId AND
vwIndicatorFact.FiscalQuarterId = IndicatorFact_NR.FiscalQuarterId AND vwIndicatorFact.CountryId = IndicatorFact_NR.CountryId AND
vwIndicatorFact.CategoryId = IndicatorFact_NR.CategoryId AND IndicatorFact_NR.IndicatorNameId = 5 AND
IndicatorFact_NR.AnalysisCategoryId = vwIndicatorFact.AnalysisCategoryId LEFT OUTER JOIN
dbo.vwIndicatorFact AS IndicatorFact_GRC2 ON IndicatorFact_GRC2.IndicatorTypeId = 2 AND vwIndicatorFact.FiscalQuarterId = IndicatorFact_GRC2.FiscalQuarterId AND
vwIndicatorFact.CountryId = IndicatorFact_GRC2.CountryId AND vwIndicatorFact.CategoryId = IndicatorFact_GRC2.CategoryId AND
IndicatorFact_GRC2.IndicatorNameId = 3 AND IndicatorFact_GRC2.AnalysisCategoryId = 2
)
AS [dbo_IndicatorFact]
This is basically multiple self joins on a particular view which contains 300k records. Our dba updated all the indexes and updated the stats, But we are still not able to execute this query quickly. If this query executes quicker, there's a chance that the cube will process quicker. The data in the view also has no inconsistencies. Need some advice on what could be the issue here.
Some background on this - this is part of migration project that we are working on. The old dev environment is able to execute the same query in about 20 seconds with similar number of records in the view. The new dev takes forever to execute the same query with the same view.
In your statement it can be anything: poor indexes, outdated statistics, bad statement, huge data....
I had similar problem and I've increased external command timeout in SSAS(it is 1 hour by default). Look here how to do it if you will not manage to optimize your query:
http://www.msbiguide.com/2013/01/how-to-increase-externalcommandtimeout-in-ssas/