104 | | SELECT |
105 | | p.id AS product_id, |
106 | | p.name AS product_name, |
107 | | p.description AS product_description, |
108 | | p.price AS product_price, |
109 | | MIN(o.quantity) AS sold_quantity, |
110 | | p.dateadded AS date_added |
111 | | FROM |
112 | | project.products p |
113 | | LEFT JOIN |
114 | | project.product_are_made_orders pamo ON p.id = pamo.id_products |
115 | | LEFT JOIN |
116 | | project.orders o ON pamo.id_orders = o.id |
117 | | GROUP BY |
118 | | p.id, p.name, p.description, p.price, p.dateadded |
119 | | ORDER BY |
120 | | sold_quantity, date_added |
121 | | LIMIT 1; |
| 104 | WITH ProductSales AS ( |
| 105 | SELECT |
| 106 | p.id AS product_id, |
| 107 | p.name AS product_name, |
| 108 | p.description AS product_description, |
| 109 | p.price AS product_price, |
| 110 | MIN(o.quantity) AS sold_quantity, |
| 111 | p.dateadded AS date_added |
| 112 | FROM |
| 113 | project.products p |
| 114 | LEFT JOIN |
| 115 | project.product_are_made_orders pamo ON p.id = pamo.id_products |
| 116 | LEFT JOIN |
| 117 | project.orders o ON pamo.id_orders = o.id |
| 118 | GROUP BY |
| 119 | p.id, p.name, p.description, p.price, p.dateadded |
| 120 | ), |
| 121 | |
| 122 | RankedProducts AS ( |
| 123 | SELECT |
| 124 | *, |
| 125 | ROW_NUMBER() OVER (ORDER BY sold_quantity, date_added) AS rn |
| 126 | FROM |
| 127 | ProductSales |
| 128 | ) |
| 129 | |
| 130 | SELECT |
| 131 | product_id, |
| 132 | product_name, |
| 133 | product_description, |
| 134 | product_price, |
| 135 | sold_quantity, |
| 136 | date_added |
| 137 | FROM |
| 138 | RankedProducts |
| 139 | WHERE |
| 140 | rn = 1; |
| 141 | |