高级MySQL查询(多个条件和分组)

时间:2015-01-22 08:58:58

标签: mysql solution

我有一个示例表,产品(列产品)分组到类别(列类别):

id    prod       price     min_age      max_customers  category
1     prod_001   $14.00    12           2              A
2     prod_002   $22.00    15           2              A
3     prod_003   $5.00     2            1              A
4     prod_004   $39.00    18           4              A
5     prod_005   $25.00    13           2              B
6     prod_006   $35.00    18           5              B
7     prod_007   $7.00     2            2              B
8     prod_008   $49.00    18           4              C
9     prod_009   $21.00    6            2              C
10    prod_010   $30.00    18           4              D
11    prod_011   $20.00    14           4              D

有列:
min_age - 该产品仅适用于此年龄段的客户 max_customers - 该产品仅适用于此数量的客户(每次购买)

我将尝试解释:我们有一个家庭有两个父母(35岁和39岁)和两个孩子(7岁和13岁)。我需要的是一个sql查询,当这个系列设置总成本(阈值)的上限时,它将为该系列提供可用的类别。我需要查询来处理这个条件:

+----------------------+--------------+
| maximum total costs: |    $99.00    |
+----------------------+--------------+
| 1st person:          | 35 years old |
| 2nd person:          | 39 years old |
| 3th person:          | 7 years old  |
| 4th person:          | 13 years old |
+----------------------+--------------+

结果应显示可用的类别:

+----------+--------+
| category | total  |
+----------+--------+
| A        | $92.00 |
+----------+--------+

如果最高总费用将更改为150.00美元,则结果应为:

+----------+---------+
| category |  total  |
+----------+---------+
| A        | $92.00  |
| B        | $102.00 |
+----------+---------+

对于"家庭B":

+----------------------+--------------+
| maximum total costs: |   $100.00    |
+----------------------+--------------+
| 1st person:          | 40 years old |
| 2nd person:          | 42 years old |
| 3th person:          | 16 years old |
+----------------------+--------------+

结果应该是:

+----------+---------+
| category |  total  |
+----------+---------+
| A        | $100.00 |
| B        | $95.00  |
| D        | $80.00  |
+----------+---------+

对于"家庭C":

+----------------------+--------------+
| maximum total costs: |   $200.00    |
+----------------------+--------------+
| 1st person:          | 60 years old |
| 2nd person:          | 65 years old |
| 3th person:          | 30 years old |
| 4th person:          | 33 years old |
| 5th person:          | 29 years old |
+----------------------+--------------+

结果应该是:

+----------+---------+
| category |  total  |
+----------+---------+
| B        | $175.00 |
+----------+---------+

还有一个重要的注意事项:如果客户是例如25岁并且在护理中有3个min_age记录(2,15和18) - 只使用最近的记录(在这种情况下为18)。如果它有问题,我可以通过额外的列max_age扩展表格来创建间隔(2 - 14,15 - 18,18 - 99)

提前感谢您的帮助!

0 个答案:

没有答案