I have the following columns as follows:
Product_ID,sale_price,sale_count,sale_state
9923842,49.99,329,CA
2940820,55.25,430,WA
2039483,32.45,23,OR
9348234,55.02,26,NY
1948134,99.42,200,VA
3948579,43.49,994,MA
2034209,934.3,430,FL
I'm trying to find the counts by Coast of states that have a sale_count of > 100 based on West Coast vs East Coast (CA and OR are West Coast, NY and MA are on the East and so on). So the result would look like:
coast,count,total_count
East,3,4
West,2,3
... where total_count is the total number of states on that coast irrespective of the sale counts
The only way I can think of is to create a table with state/coast mapping and then use that as a reference. Is there a better way without having to resort to temp tables?
This is currently being done in MySQL but I'd like a platform agnostic solution as this may be ported to another platform soon.
Here's a standard ANSI way to do it, that should work I hope
SELECT 'East' AS Coast,
SUM(CASE WHEN sale_count > 100 THEN 1 ELSE 0 END) AS cnt,
COUNT(*) AS total_count
FROM table
WHERE sale_state IN ('NY','MA')
UNION ALL
SELECT 'West' AS Coast,
SUM(CASE WHEN sale_count > 100 THEN 1 ELSE 0 END) AS cnt,
COUNT(*) AS total_count
FROM table
WHERE sale_state IN ('CA','OR')
I am from EU so I let you complete the states' lists...
Edit: This one contains count and total_count as described in your comment above
SELECT coast, SUM(sale_cnt) AS count, COUNT(*) AS total_count
FROM T LEFT JOIN
(SELECT sale_state,
CASE
WHEN sale_state IN ('CA','WA','OR') THEN 'West'
WHEN sale_state IN ('NY','VA','MA','FL') THEN 'East' END AS coast,
CASE
WHEN sale_count > 100 THEN 1
ELSE 0 END AS sale_cnt
FROM T) C
ON T.sale_state = C.sale_state
GROUP BY coast
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.