Aliasing a CASE statement - mysql

I would need your help to fix a problem I'm facing.. I'm using a CASE function and aliasing its result by adding "AS 'RESULT'" after its "END".
Event though the query seems to run, I'm still getting the following warnings through phpmyadmin :
Unrecognized keyword (near AS)
Unexpected token (near 'RESULT')
I have no idea on why I'm getting this...I would appreciate your help to highlight my mistake ;-)
SELECT
app_fd_List_of_components.c_component,
app_fd_List_of_orders.c_package,
app_fd_List_of_orders.c_status,
app_fd_List_of_orders.dateCreated,
app_fd_List_of_orders.c_orderId,
app_fd_List_of_orders.Id,
temptablename.datetime AS Int_Date,
temptablename2.datetime AS Prdw3_Date,
#counterStatus := IF(
app_fd_List_of_orders.c_status <> 'Deployment completed',
IF(
temptablename.datetime IS NOT NULL,
'Counting',
'Initializing'
),
'Complete'
) AS 'Counter_status',
#counter := IF(
app_fd_List_of_orders.c_status <> 'Deployment completed',
IF(
temptablename.datetime IS NOT NULL,
(
35 - DATEDIFF(
CURRENT_DATE(), temptablename.datetime)
),
'n/a'
),
DATEDIFF(
temptablename2.datetime,
temptablename.datetime
)
) AS 'Counter',
CASE (WHEN(
(#counterStatus = 'Counting') AND(#counter < 0)
) THEN "black" WHEN(
(#counterStatus = 'Counting') AND(#counter > 5)
) THEN "green" WHEN(
(#counterStatus = 'Counting') AND(-1 < #counter < 5)
) THEN "orange" WHEN(
(#counterStatus = 'Complete') AND(#counter > 35)
) THEN "black" WHEN(
(#counterStatus = 'Complete') AND(#counter < 35)
) THEN "green" ELSE "n/a")
END AS 'RESULT'
FROM
app_fd_List_of_orders
JOIN app_fd_List_of_components ON
app_fd_List_of_orders.c_component = app_fd_list_of_components.id
LEFT JOIN(
SELECT app_form_data_audit_trail.datetime,
app_form_data_audit_trail.data
FROM
app_form_data_audit_trail
WHERE
SUBSTRING_INDEX(
SUBSTRING_INDEX(
app_form_data_audit_trail.data,
'"opdetails":"',
-1
),
'"',
1
) = 'int'
) AS temptablename
ON
app_fd_list_of_orders.c_orderid = SUBSTRING_INDEX(
SUBSTRING_INDEX(
temptablename.data,
'"orderId":"',
-1
),
'"',
1
)
LEFT JOIN(
SELECT app_form_data_audit_trail.datetime,
app_form_data_audit_trail.data
FROM
app_form_data_audit_trail
WHERE
SUBSTRING_INDEX(
SUBSTRING_INDEX(
app_form_data_audit_trail.data,
'"opdetails":"',
-1
),
'"',
1
) = 'prdw3'
) AS temptablename2
ON
app_fd_list_of_orders.c_orderid = SUBSTRING_INDEX(
SUBSTRING_INDEX(
temptablename2.data,
'"orderId":"',
-1
),
'"',
1
)

Have you tried removing the parentheses around the CASE statement?
CASE
WHEN #counterStatus = 'Counting' AND #counter < 0 THEN "black"
WHEN #counterStatus = 'Counting' AND #counter > 5 THEN "green"
WHEN #counterStatus = 'Counting' AND -1 < #counter < 5 THEN "orange"
WHEN #counterStatus = 'Complete' AND #counter > 35 THEN "black"
WHEN #counterStatus = 'Complete' AND #counter < 35 THEN "green"
ELSE "n/a"
END AS 'RESULT'
EDIT: I'm also not sure this is possible:
WHEN #counterStatus = 'Counting' AND -1 < #counter < 5 THEN "orange"
It may need to be written as:
WHEN #counterStatus = 'Counting' AND -1 < #counter AND #counter < 5 THEN "orange"

Related

How to parse a string and get the value after "=" character

So I have string that should contains "Object.Name" once in a row , if I see it ,I have to get the value after "=" character. If doesn't match it anywhere in the string i should move hardcoded value.
Here is example of the string:
Object.Name=ASDD||Product.Name=DSA
Product.Name=QWE||Object.Name=WSXS
Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ
I know that I should use case for that but doesn't know how to proceed the string
case
when (match the string ) then (value after the "=")
else (hardcoded value)
end
In Oracle, you can use:
SELECT value,
CASE
WHEN start_pos = 0
THEN NULL
ELSE SUBSTR(
'||' || value || '||',
start_pos + LENGTH('||Object.Name='),
end_pos - start_pos - LENGTH('||Object.Name=')
)
END AS object_name
FROM (
SELECT value,
INSTR(
'||' || value || '||',
'||Object.Name='
) AS start_pos,
INSTR(
'||' || value || '||',
'||',
INSTR('||' || value || '||', '||Object.Name=')+LENGTH('||Object.Name=')
) AS end_pos
FROM table_name
)
Which, for the sample data:
CREATE TABLE table_name (value) AS
SELECT 'Object.Name=ASDD||Product.Name=DSA' FROM DUAL UNION ALL
SELECT 'Product.Name=QWE||Object.Name=WSXS' FROM DUAL UNION ALL
SELECT 'Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ' FROM DUAL;
Outputs:
VALUE
OBJECT_NAME
Object.Name=ASDD||Product.Name=DSA
ASDD
Product.Name=QWE||Object.Name=WSXS
WSXS
Storage.Name=12345||Object.Name=WERR||Product.Name=QAZ
WERR
db<>fiddle here
Since you changed the tags, in MySQL:
SELECT value,
CASE
WHEN start_pos = 0
THEN NULL
ELSE SUBSTRING(
CONCAT('||', value, '||'),
start_pos + LENGTH('||Object.Name='),
end_pos - start_pos - LENGTH('||Object.Name=')
)
END AS object_name
FROM (
SELECT value,
LOCATE(
'||Object.Name=',
CONCAT('||', value, '||')
) AS start_pos,
LOCATE(
'||',
CONCAT('||', value, '||'),
LOCATE('||Object.Name=', CONCAT('||', value, '||'))
+ LENGTH('||Object.Name=')
) AS end_pos
FROM table_name
) t
db<>fiddle here

Join nested relationship as columns

I need some help with my SQL. I am attempting to get the following rows...
ID
Sender
Code 1
Code 1 Score
Code 2
Code 2 Score
1
John Doe
AB
80
BA
87
2
Jane Doe
CD
45
DC
99
The code columns are the hard part. This is the relationships
Conversation -> Messages -> Highlights -> Codes.
Messages have a conversation_id
Messages Highlights have a message_id
Codes have a highlight_id
One conversation has many messages, Each Message has many Highlights, and any highlights have many codes.
SELECT
conversations.id,
CONCAT(senders.first_name, ' ', senders.last_name) as 'Sender Name'
conversations.created_at AS 'Start Date',
FROM
conversations
LEFT JOIN users AS senders ON sender.id = conversations.participant_1
LEFT JOIN users AS recipient ON recipient.id = conversations.participant_2
GROUP BY
conversations.name
I cannot figure out how to include the codes into the results as columns that a paired (Code 1 Name, Code Score).
The above query works to get the first few columns, but I'd like to join in the codes. Any help would be appreciated.
I have an idea to make use of row_number to create multiple columns
SELECT m.highlight_id,
MAX( CASE WHEN RN = 1 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 1 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 2 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 2 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 3 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 3 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 4 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 4 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 5 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 5 THEN m.code_score ELSE '' END )
FROM
(
SELECT
b.highlight_id, b.code_name, b.code_score, (CASE WHEN #T = b.highlight_id THEN #RN := #RN + 1 ELSE #RN := 1 END ) AS RN, #T := b.highlight_id
FROM highlights a
JOIN codes b ON a.highlight_id = b.highlight_id
JOIN (SELECT #T := '', #RN := 0) u
ORDER BY a.highlight_id, b.code_name
) m
GROUP BY m.highlight_id
;
If you are using MySQL 8.0, it's simpler
SELECT m.highlight_id,
MAX( CASE WHEN RN = 1 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 1 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 2 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 2 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 3 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 3 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 4 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 4 THEN m.code_score ELSE '' END ),
MAX( CASE WHEN RN = 5 THEN m.code_name ELSE '' END ),
MAX( CASE WHEN RN = 5 THEN m.code_score ELSE '' END )
FROM (
SELECT b.highlight_id, b.code_name, b.code_score, ROW_NUMBER() OVER(PARTITION BY b.highlight_id ORDER BY b.code_name) RN
FROM highlights a
JOIN codes b ON a.highlight_id = b.highlight_id
) m
GROUP BY m.highlight_id
;

Creating function error sql server 2008

I want to create a fucntion, but getting error.
below is query:
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS TABLE
AS BEGIN
DECLARE
#TIMER_START_ACTIVITY_ID INT,
#TIMER_START_ACTIVITY_COMPLETED_ON DATETIME,
#TIMER_END_ACTIVITY_ID INT,
#TIMER_END_ACTIVITY_COMPLETED_ON DATETIME,
#SLA_TIME_SCHEDULE_IN_DAYS INT,
#SLA_DISPLAY VARCHAR(20),
#START_DATE DATETIME,
#END_DATE DATETIME,
#BUSINESS_START_TIME VARCHAR(10),
#BUSINESS_END_TIME VARCHAR(10),
#BUSINESS_HOURS INT,
#SLA_CUT_OFF_TIME VARCHAR(10),
#IS_OBJECT_STATUS_IS_TERMINAL INT,
#COMPLETED_ACTION_ID INT,
#UNCHECKED_ACTION_ID INT,
#DAY_ADDED INT
SELECT #IS_OBJECT_STATUS_IS_TERMINAL = CASE when wos.FLG_STATUS_TYPE = 'W' THEN 0 ELSE 1 END
FROM WF.WF_OBJECT_INSTANCE woi
INNER JOIN WF.WF_OBJECT_STATUS wos ON wos.OBJECT_STATUS_ID = woi.OBJECT_STATUS_ID
WHERE woi.LINK_PK_ID = #OBJECT_PK_ID
SET #SLA_TIME_SCHEDULE_IN_DAYS = (SELECT CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN lr.RUSH_NO_OF_DAYS ELSE s.NUM_OF_DAYS END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #SLA_DISPLAY = (SELECT
CASE WHEN s.SLA_SCHEDULE_ID = 1 THEN s.DISPLAY_NAME + ' (' + CAST(lr.RUSH_NO_OF_DAYS AS VARCHAR) + ')' ELSE s.DISPLAY_NAME END --1= [RUSH]
FROM loan.LOAN_REQUEST lr
INNER JOIN WF.WF_SLA_SCHEDULE s
ON s.SLA_SCHEDULE_ID = ISNULL(lr.SLA_SCHEDULE_ID, 2) --{2= SLA-Schedule 5 Days}
WHERE lr.LOAN_REQUEST_ID = #OBJECT_PK_ID)
SET #BUSINESS_START_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_START_TIME')
SET #BUSINESS_END_TIME = (SELECT s.CONFIG_VALUE FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'BUSINESS_END_TIME')
SET #BUSINESS_HOURS = (SELECT CAST(DATEDIFF(hour, CAST(#BUSINESS_START_TIME AS DATETIME), CAST(#BUSINESS_END_TIME AS DATETIME)) AS INT))
SET #SLA_CUT_OFF_TIME = (SELECT DATEPART(hour, CAST(s.CONFIG_VALUE AS TIME)) FROM SYS_CONFIG_ENTRY s WHERE s.NAME = 'SLA_CUT_OFF_TIME')
SET #COMPLETED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_COMPLETED')
SET #UNCHECKED_ACTION_ID = (SELECT ACTION_TYPE_ID FROM WF.WF_ACTION_TYPE WHERE NAME = 'ACTIVITY_UNCHECKED')
--GET SLA TIMER ACTIVITY IDs
SELECT #TIMER_START_ACTIVITY_ID = t.START_ACTIVITY_ID,
#TIMER_END_ACTIVITY_ID = t.END_ACTIVITY_ID
FROM [WF].WF_TIMER t
WHERE t.NAME = 'SLA_TIMER'
--Get START ACTIVITY ON
SELECT #TIMER_START_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_START_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
--AND
----{
--0 = ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
-- FROM WF.WF_OBJECT_ACTIVITY_HISTORY
-- WHERE LINK_PK_ID = #OBJECT_PK_ID
-- AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
-- AND ACTION_ID = #COMPLETED_ACTION_ID
-- ORDER BY ACTION_ON DESC), 0)
----}
ORDER BY ACTION_ON DESC
--Get END ACTIVITY ON
SELECT #TIMER_END_ACTIVITY_COMPLETED_ON = ACTION_ON
FROM [WF].WF_OBJECT_ACTIVITY_HISTORY woah
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND woah.ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #COMPLETED_ACTION_ID
AND
--{
woah.APPLICATION_HISTORY_ID > ISNULL((SELECT TOP 1 ISNULL(APPLICATION_HISTORY_ID, 0)
FROM WF.WF_OBJECT_ACTIVITY_HISTORY
WHERE LINK_PK_ID = #OBJECT_PK_ID
AND ACTIVITY_ID = #TIMER_END_ACTIVITY_ID
AND ACTION_ID = #UNCHECKED_ACTION_ID
ORDER BY ACTION_ON DESC
), 0)
--}
ORDER BY ACTION_ON DESC
--TO DO
--SET #TIMER_START_ACTIVITY_COMPLETED_ON = '2014-05-15 02:40:21.100'
--SET #TIMER_END_ACTIVITY_COMPLETED_ON = '2014-05-14 12:40:21.100'
SET #START_DATE = #TIMER_START_ACTIVITY_COMPLETED_ON
SET #DAY_ADDED = #SLA_TIME_SCHEDULE_IN_DAYS -- SLA Schedule Days
+ CASE WHEN DATEPART(hour, #TIMER_START_ACTIVITY_COMPLETED_ON) >= #SLA_CUT_OFF_TIME THEN 0 ELSE -1 END -- SLA Cut Off Time
SET #END_DATE = #START_DATE + #DAY_ADDED
--Exclud Holidays
--{
DECLARE #START_ON_DATE DATETIME = CAST(#START_DATE AS DATE)
WHILE #DAY_ADDED > 0
BEGIN
SELECT #END_DATE = #START_ON_DATE + #DAY_ADDED
--COUNT NO OF HOLIDAYS IF FALLING WITHIN START-DATE AND END-DATE
SELECT #DAY_ADDED = COUNT(*) FROM [WF].WF_CALENDAR WC --HOLIDAY LIST
WHERE WC.DATE BETWEEN #START_ON_DATE+1 AND #END_DATE AND (WC.IS_WEEKEND = 1 OR WC.IS_HOLIDAY = 1)
SET #START_ON_DATE = #END_DATE
END
--}
SET #END_DATE = (CAST(CAST(CAST(#END_DATE AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME))
;WITH TIMER_CTE AS (
SELECT #START_DATE AS OBJECT_CREATED_ON,
#END_DATE AS OBJECT_END_ON,
DIFFERENCE_IN_DAYS = DATEDIFF(dd, GETDATE(), #END_DATE),
TODAY_REMAINING_MINUTES =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))
ELSE 0 END,
TODAY_REMAINING_HOURS =
CASE WHEN CONVERT(VARCHAR(10), #END_DATE, 112) >= CONVERT(VARCHAR(10), GETDATE(), 112)
THEN (DATEDIFF(minute, GETDATE(), (CAST(CAST(CAST(GETDATE() AS DATE) AS DATETIME) + CAST(#BUSINESS_END_TIME AS TIME) AS DATETIME)))/60)
ELSE 0 END
)
RETURN (
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY,
SLA_DUE = CONVERT(VARCHAR(10), CONVERT(DATETIME, tc.OBJECT_END_ON, 1), 101),
#BUSINESS_END_TIME AS BUSINESS_END_TIME,
SLA_START_ACTIVITY_CHECKED_ON = tc.OBJECT_CREATED_ON,
SLA_END_ACTIVITY_CHECKED_ON = #TIMER_END_ACTIVITY_COMPLETED_ON,
SLA_MISSED = CASE WHEN
--TODAY_REMAINING_MINUTES <= 0
--AND CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
--OR
( GETDATE()> #END_DATE)
OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 'Missed' ELSE NULL END,
tc.TODAY_REMAINING_HOURS,
tc.TODAY_REMAINING_MINUTES,
LAST_DAY_TIME_REMAINING =
CASE
WHEN #TIMER_END_ACTIVITY_COMPLETED_ON <= #END_DATE THEN 'Successful Completed'
WHEN CONVERT(VARCHAR(10), #END_DATE, 112) = CONVERT(VARCHAR(10), GETDATE(), 112)
THEN
CASE WHEN
tc.TODAY_REMAINING_HOURS <=0 AND tc.TODAY_REMAINING_MINUTES > 0 THEN
CASE WHEN tc.TODAY_REMAINING_MINUTES = 1 THEN CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' min remaining'
ELSE CAST(tc.TODAY_REMAINING_MINUTES AS VARCHAR) + ' mins remaining' END
WHEN tc.TODAY_REMAINING_HOURS =1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hour remaining'
WHEN tc.TODAY_REMAINING_HOURS >1 THEN CAST(tc.TODAY_REMAINING_HOURS AS VARCHAR) + ' hours remaining'
ELSE NULL
END
ELSE NULL
END,
REMAINING_DAYS = CASE WHEN tc.DIFFERENCE_IN_DAYS <=0 THEN '0 day'
WHEN tc.DIFFERENCE_IN_DAYS > 1 THEN CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' days '
ELSE CAST(tc.DIFFERENCE_IN_DAYS AS VARCHAR) + ' day ' END
FROM TIMER_CTE tc
)
END;
GO
I am getting this error:
Msg 156, Level 15, State 1, Procedure WFSlaTimer, Line 144
Incorrect syntax near the keyword 'RETURN'.
Msg 178, Level 15, State 1, Procedure WFSlaTimer, Line 144
A RETURN statement with a return value cannot be used in this context.
Msg 102, Level 15, State 31, Procedure WFSlaTimer, Line 189
Incorrect syntax near 'BEGIN'.
Any help please
There are two kind of function that return table. the inline function and multi-statement function. Yours is multi-statement. Here is the syntax for this:
--Transact-SQL Multistatement Table-valued Function Syntax
CREATE FUNCTION [ schema_name. ] function_name
( [ { #parameter_name [ AS ] [ type_schema_name. ] parameter_data_type
[ = default ] [READONLY] }
[ ,...n ]
]
)
RETURNS #return_variable TABLE <table_type_definition>
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN
END
[ ; ]
For more information refer to CREATE FUNCTION (Transact-SQL) BOL documentation.
You have to define the returned table's structure (fields and data types)
1) Add a variable name to the function definition (#tableVariable in the above example).
2) Fill the table definition (columns and datatypes)
3) Modify your function to insert the result into the defined table variable, then use an empty RETURN statement when the function should return.
1st step
CREATE FUNCTION WFSlaTimer
(
#OBJECT_PK_ID INT = 110
)
RETURNS #tableVariable TABLE (
IS_SHOW_SLA INT,
StartDate DATETIME2,
EndDate DATETIME2
/** List all of your returned columns like when you creating a table **/
)
AS
BEGIN
/** Do your stuff **/
INSERT INTO #tableVariable ( /* field list */) VALUES (/* value list */)
-- OR --
INSERT INTO #tableVariable ( /* field list */)
SELECT /* FieldList */ FROM myCTE
RETURN
END
2nd step
Modify your RETURN () statement like this:
INSERT INTO #tableVanriable (IS_SHOW_SLA , StartDate , EndDate)
SELECT
IS_SHOW_SLA = CASE WHEN #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
--OR #IS_OBJECT_STATUS_IS_TERMINAL = 1
--OR #TIMER_START_ACTIVITY_COMPLETED_ON IS NULL
THEN 0
ELSE 1 END,
#START_DATE AS [START_DATE], #END_DATE AS [END_DATE],
SLA_TYPE = #SLA_DISPLAY
/** .... **/
FROM TIMER_CTE tc
/** 3rd step **/
RETURN

Query works perfect in phpmyadmin but only returns true/1 when fetching with php

I have this query that does exactly what i want in phpmyadmin, it returns the number of visits my site has had. ex: visitorCount: 2204
set #last_uid = 0;
set #last_tm = '00:00';
set #last_vid = 0;
SELECT MAX(
CASE WHEN #last_uid = visitorid AND cast( #last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN
if( (#last_tm := timestamp ), #last_vid, #last_vid)
ELSE
if( (#last_uid := visitorid) + (#last_vid := #last_vid+1) +(#last_tm := timestamp ),#last_vid, #last_vid )
END
) as visitorCount
FROM visits v
ORDER BY timestamp DESC, visitorid
When i try to execute this query from PHP however it doesen't work, i have tested with a regular php mysql connection and with cakephp $this->Model->query(); without any success, all i get from the query is "1" or true. Whats wrong?
$query = "set #last_uid = 0;
set #last_tm = '00:00';
set #last_vid = 0;
SELECT MAX(
CASE WHEN #last_uid = visitorid AND cast( #last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN
if( (#last_tm := timestamp ), #last_vid, #last_vid)
ELSE
if( (#last_uid := visitorid) + (#last_vid := #last_vid+1) +(#last_tm := timestamp ),#last_vid, #last_vid )
END
)
FROM visits v
ORDER BY timestamp DESC, visitorid";
$con = mysql_connect("host", "user", "pass");
if (!$con) {
die(mysql_error());
}
mysql_select_db("dbname", $con);
$result = mysql_query($query);
print_r(mysql_fetch_row($result));
Gives me the error message:
mysql_fetch_row() expects parameter 1 to be resource, boolean given
I'm not sure if it is because you are executing multiple statements but try combining it into one,
SELECT MAX(CASE WHEN #last_uid = visitorid AND cast( #last_tm as datetime) >= subtime( timestamp, '01:00' )
THEN if((#last_tm := timestamp), #last_vid, #last_vid)
ELSE if((#last_uid := visitorid) + (#last_vid := #last_vid+1) + (#last_tm := timestamp), #last_vid, #last_vid )
END)
FROM visits v,
(SELECT #last_uid := 0, #last_tm := '00:00', #last_vid := 0;) x
ORDER BY timestamp DESC, visitorid

If statement to distinguish which "Case" query should be added to select query

I'm stacked on following query. I need to create an if statement or something similar to distinguish which "CASE" should be added to my select query.
If page_type = 'Region' or 'City' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 2
Then 'True' Else 'False' End as 'correct lp' , )
Elseif page_type = 'Item' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 3
Then 'True' Else 'False' End as 'correct lp' , )
Elseif page_type = 'POI (Alle)' add this to the query:
( CASE When landing_page like concat('%',path_id,'%') and
(LENGTH(landing_page) - LENGTH(REPLACE(landing_page, '/' ,'')) / LENGTH('/')) = 3 and
'Hotel' NOT IN landing_page
Then 'True' Else 'False' End as 'correct lp' , )
Case queries should be added to the following query according to if outcome:
SELECT
MONTHNAME(k.crawl_date) As 'Month',
YEAR(k.crawl_date) As 'Year',
WEEKOFYEAR(k.crawl_date) As 'Week',
k.landing_page,
k.pos,
CASE WHEN k.pos = 0 THEN 'No Rank' WHEN k.pos < 4 THEN 'Top 3' WHEN k.pos < 11 THEN 'Page 1'
WHEN k.pos < 21 THEN 'Page 2' WHEN k.pos < 31 THEN 'Page 3' WHEN k.pos < 41 THEN 'Page 4'
WHEN k.pos < 51 THEN 'Page 5' WHEN k.pos < 61 THEN 'Page 6' WHEN k.pos < 71 THEN 'Page 7'
WHEN k.pos < 81 THEN 'Page 8' WHEN k.pos < 91 THEN 'Page 9' WHEN k.pos < 101 THEN 'Page 10'
WHEN k.pos < 111 THEN 'Page 11' END as 'Page',
k.path_id,
k.domain,
x.keyword,
x.engine_id,
l.bucket,
l.page_type,
l.item_label
FROM
xovi_stats k
LEFT JOIN xovi_keywords x ON k.keyword_id = x.id
LEFT JOIN xovi_labels l ON l.id = x.label_id
You can nest CASE clauses like this:
SELECT
CASE
WHEN (page_type IN ('Region', 'City')) THEN
CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END
WHEN (page_type = 'Item') THEN
CASE
...
END
WHEN (page_type = 'POI (Alle)') THEN
CASE
...
END
END AS lp,
MONTHNAME(k.crawl_date) As 'Month', -- other fields
...
Or you can also nest IF(), as you suggest:
SELECT
IF ( (page_type IN ('Region', 'City')),
-- if (page_type IN ('Region', 'City')) then
CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END,
-- else
IF ( (page_type = 'Item'),
-- if (page_type = 'Item') then
CASE
...
END,
-- else
IF ( page_type = 'POI (Alle)',
-- if (page_type = 'POI (Alle)') then
CASE
...
END,
-- else
NULL
)
)
) AS lp,
MONTHNAME(k.crawl_date) As 'Month', -- other fields
...
Off-topic notes:
you can replace your two-branch CASE statements with simple IF():
SELECT CASE
WHEN landing_page LIKE ... THEN 'True'
ELSE 'False'
END AS alias ;
-- strictly equivalent to
SELECT IF(
landing_page LIKE ...,
'True',
'False'
) AS alias ;
you can replace your large existing CASE with:
CASE
WHEN k.pos = 0 THEN 'No Rank'
WHEN k.pos < 4 THEN 'Top 3'
ELSE CONCAT('Page ', (k.pos -1) DIV 10 +1 )
END AS 'Page'