我对以下查询有所了解。我需要创建一个if语句或类似的东西来区分应该将哪个“CASE”添加到我的选择查询中。
If page_type = 'Region' or 'City'
将此内容添加到查询中:
( 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'
将此内容添加到查询中:
( 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)'
将此内容添加到查询中:
( 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' , )
案例查询应根据if
结果添加到以下查询中:
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
答案 0 :(得分:1)
您可以像这样嵌套CASE
子句:
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
...
或者您也可以按照建议嵌套IF()
:
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
...
偏离主题的说明:
CASE
替换您的双分支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 ;
CASE
: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'