复杂SQL查询实例-5种普惠产品必须显示...

时间:2021-07-31 09:17:51

复杂SQL需求:

1.查询productCode in (1, 2, 4, 5, 7)五种

2.5种产品必须固定显示,优先显示procuct_status='1'在售产品,在售产品卖完则售罄产品顶上来,即每种产品必须显示一条,不可空挡

3.在售取时间最早的一条,售罄取时间最晚的一条

SELECT
procuct_starttime,
procuct_starttime AS "product_saletime",
product_no,
o.product_code,
product_name,
marketing_type,
pay_type,
is_transfer,
close_period,
procuct_status,
product_recommend,
trade_type,
IFNULL(
(
SELECT
t.star_img
FROM
tb_crm_activity_product_info f,
tb_crm_activity_resource_info g,
tb_crm_star_information t
WHERE
product_no = f.product_id
AND f.acti_id = g.acti_id
AND g.resource_id = t.id
),
'http://www.gougou.com.cn'
) url,
IFNULL(
(
SELECT
COUNT(*)
FROM
tb_customer_order co
WHERE
co.product_no = o.product_no
GROUP BY
co.product_no
),
0
) buyCount,
IFNULL(procuct_aroe, 0) annualizedRate,
product_addonrate,
IFNULL(procuct_min_amount, 0) minPurchaseAmount,
procuct_amount financingAmount,
IFNULL(product_amount_buy, 0) currentAmount,
FORMAT(
IFNULL(product_amount_buy, 0) * 100 / procuct_amount,
2
) amountScale,
CASE
WHEN FORMAT(
IFNULL(product_amount_buy, 0) * 100 / procuct_amount,
2
) >= 100 THEN
'1'
ELSE
'0'
END eee,
procuct_type productType,
procuct_day productDay,
procuct_summary productSummary,
CASE
WHEN product_amount_buy >= procuct_amount THEN
1
ELSE
0
END oindex, IF (
o.product_recommend = 'Y',
1,
0
) ooo
FROM
(
SELECT
pt.*
FROM
tb_product_type pt
INNER JOIN (
SELECT
MAX(product_no) product_no
FROM
tb_product_type a
INNER JOIN (
SELECT
product_code,
MIN(procuct_starttime) procuct_starttime
FROM
tb_product_type
WHERE
marketing_type = '1'
AND procuct_status = '1'
AND product_amount_buy < procuct_amount
AND product_code IN (1, 2, 4, 5, 7)
GROUP BY
product_code
) b ON a.product_code = b.product_code
AND a.procuct_starttime = b.procuct_starttime
GROUP BY
a.product_code
UNION ALL
SELECT
MAX(product_no) product_no
FROM
tb_product_type a
INNER JOIN (
SELECT
p1.product_code,
MAX(procuct_starttime) procuct_starttime
FROM
tb_product_type p1
WHERE
NOT EXISTS (
SELECT
1
FROM
tb_product_type p2
WHERE
marketing_type = '1'
AND procuct_status = '1'
AND product_amount_buy < procuct_amount
AND p1.product_code = p2.product_code
)
AND marketing_type = '1'
AND product_code IN (1, 2, 4, 5, 7)
GROUP BY
product_code
) b ON a.product_code = b.product_code
AND a.procuct_starttime = b.procuct_starttime
GROUP BY
a.product_code
) pt2 ON pt.product_no = pt2.product_no
) o
ORDER BY
ooo DESC,
product_code ASC;