简体   繁体   中英

What is the function to divide 2 values from the same column with conditions

I would like to return my total return divided by my total sale which are under the same column

select
(select count(order_type_id) from ods_emea_all.order_emea 
where order_type_id in ('Return', 'RETURN')
and brand_cd =('PB')
and iso_country_cd IN ('IT', 'ES', 'GB', 'FR', 'DE'))*100/
(select count(order_type_id )
from ods_emea_all.order_emea 
where order_type_id in ('Sale','SALE')
and brand_cd =('PB')
and iso_country_cd IN ('IT', 'ES', 'GB', 'FR', 'DE'))
 AS brand_return
from ods_emea_all.order_emea

If you have the following table with contents:

CREATE TABLE order_emea (
  order_type_id VARCHAR(100),
  brand_cd VARCHAR(100),
  iso_country_cd VARCHAR(100)
);

INSERT INTO order_emea VALUES
  ('Sale', 'PB', 'IT'),
  ('SALE', 'PB', 'FR'),
  ('Sale', 'PB', 'IT'),
  ('sale', 'PB', 'ES'),
  ('SALe', 'PB', 'ES'),
  ('sAle', 'PB', 'GB'),
  ('saLe', 'PB', 'FR'),
  ('sale', 'PB', 'DE'),
  ('Sale', 'PB', 'DE'),
  ('sale', 'PB', 'FR'),
  ('Return', 'PB', 'FR'),
  ('RETURN', 'PB', 'FR'),
  ('return', 'PB', 'GB'),
  ('REturn', 'PB', 'IT'),
  ('rEturn', 'PB', 'IT');

The following query will get you what you want:

WITH base_table_n_returns_to_n_sales AS (
  SELECT
    SUM(CASE WHEN
      LOWER(order_type_id) = 'return'
      AND LOWER(brand_cd) = 'pb'
      AND LOWER(iso_country_cd) IN ('IT', 'ES', 'GB', 'FR', 'DE')
    THEN 1 ELSE 0 END) AS n_returns,
    SUM(CASE WHEN
      LOWER(order_type_id) = 'sale'
      AND LOWER(brand_cd) = 'pb'
      AND LOWER(iso_country_cd) IN ('IT', 'ES', 'GB', 'FR', 'DE')
    THEN 1 ELSE 0 END) AS n_sales
  FROM order_emea
)

SELECT
  *,
  n_returns / CAST(NULLIF(n_sales, 0) AS FLOAT) AS ratio_n_returns_to_n_sales
FROM base_table_n_returns_to_n_sales

See this fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM