SQL Server:基于多个条件在组之间搜索

问题描述 投票:0回答:1

我有下面的Product表。我正在尝试根据多个条件查找产品。

这是我的示例数据:

+-----------+------------+------------------+----------------+-----------------+-------+
| productid |  barcode   |   product_name   | is_product_new | premium_service | price |
+-----------+------------+------------------+----------------+-----------------+-------+
|         1 | 1122334455 | rubber duck      |              0 |               0 |  3,00 |
|         2 | 1122334455 | rubber duck      |              1 |               0 |  4,00 |
|         3 | 1122334455 | rubber duck      |              1 |               0 |  5,00 |
|         4 | 1122334455 | rubber duck      |              1 |               1 |  6,00 |
|         5 | 2233445566 | barbie doll      |              1 |               0 | 10,00 |
|         6 | 2233445566 | barbie doll      |              0 |               0 |  8,00 |
|         7 | 3344556677 | actionman figure |              1 |               1 | 22,00 |
|         8 | 3344556677 | actionman figure |              1 |               0 | 18,00 |  
|         9 | 3344556677 | actionman figure |              0 |               0 |  6,00 |
|        10 | 3344556677 | actionman figure |              0 |               0 |  5,00 |
+-----------+------------+------------------+----------------+-----------------+-------+

共有三种产品。

我想在提供优质服务的产品中搜索具有最低新价格,最低使用价格和优质价格的产品。

我的预期结果是:

+-----------+------------+------------------+------------------+------------------+-----------------+
| productid |  barcode   |   product_name   | lowest_old_price | lowest_new price |   premium_price |
+-----------+------------+------------------+------------------+------------------+-----------------+
|         1 | 1122334455 | rubber duck      |             3.00 |             4.00 |            6.00 |
|         7 | 3344556677 | actionman figure |             5.00 |            18.00 |           22.00 |
+-----------+------------+------------------+------------------+------------------+-----------------+

我试图用group by和haveing子句编写查询,但结果没有任何意义!即使我不确定我需要使用哪个功能/子句!

需要您的帮助...

sql sql-server having-clause
1个回答
1
投票

嗯。 。 。如果我正确理解,这是带有having子句的条件聚合:

select min(productid) as productid, barcode, product_name
       min(case when is_product_new = 0 then price end) as old_price,
       min(case when is_product_new = 1 then price end) as new_price,
       min(case when premium_service = 1 then price end) as premium_price
from products p
group by productid, barcode, product_name
having max(premium_service) = 1;
© www.soinside.com 2019 - 2024. All rights reserved.