如何选择包含特定值的组?

时间:2021-02-22 11:51:15

标签: mysql

我有一个订单表,其格式如下:

╔══════════╦══════════╦══════════╦═══════╦══════════════╦═══════════════╗
║ Order ID ║ Subtotal ║ Shipping ║ Total ║ Product Name ║ Product Price ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 1        ║ 30       ║ 5        ║ 35    ║ Apple        ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 1        ║          ║          ║       ║ Banana       ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 1        ║          ║          ║       ║ Coffee       ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 2        ║ 30       ║ 5        ║ 35    ║ Peach        ║ 20            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 2        ║          ║          ║       ║ Banana       ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 3        ║ 20       ║ 3        ║ 23    ║ Peach        ║ 20            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 4        ║ 40       ║ 10       ║ 50    ║ Apple        ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 4        ║          ║          ║       ║ Coffee       ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 4        ║          ║          ║       ║ Peach        ║ 20            ║
╚══════════╩══════════╩══════════╩═══════╩══════════════╩═══════════════╝

所有订单号都是总计 - 小计和运费,下面的行为空白。

我正在尝试调查特定产品的销售情况。

例如,我想要一个查询,该查询选择包含“香蕉”的所有订单,并返回订单的小计、运费和总额以及产品价格(有时不在同一行上) :

即它会返回这个:

╔══════════╦══════════╦══════════╦═══════╦══════════════╦═══════════════╗
║ Order ID ║ Subtotal ║ Shipping ║ Total ║ Product Name ║ Product Price ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 1        ║ 30       ║ 5        ║ 35    ║ Banana       ║ 10            ║
╠══════════╬══════════╬══════════╬═══════╬══════════════╬═══════════════╣
║ 2        ║ 30       ║ 5        ║ 35    ║ Banana       ║ 10            ║
╚══════════╩══════════╩══════════╩═══════╩══════════════╩═══════════════╝

1 个答案:

答案 0 :(得分:1)

您可以将表加入到自身中:

select 
  b.`Order ID`,
  max(s.Subtotal) as 'Subtotal',
  max(s.Shipping) as 'Shipping',
  max(s.Total) as 'Total',
  b.`Product Name`,
  b.`Product Price`
from orders b
  join orders s on s.`Order ID`=b.`Order ID`
where b.`Product Name`='Banana'
group by 
  b.`Order ID`, 
  b.`Product Name`,
  b.`Product Price`

看到一个 dbfiddle