简体   繁体   English

需要帮助 MS Access Select 请求使用 2 个表

[英]Need help for MS Access Select Request using 2 tables

For a "products reservation system", I have 2 tables:对于“产品预订系统”,我有 2 张桌子:

  • "RD", for global reservations data (fieds: ID, CustomerID, Date, ...) “RD”,用于全球预订数据(字段:ID、CustomerID、Date,...)
  • "RP", for reserved products data per reservation (fields: ID, RD_ID, ProductID, Status, ...). “RP”,用于每个预留的预留产品数据(字段:ID、RD_ID、ProductID、状态...)。 RD_ID fits with the ID in RD table (field for joining). RD_ID 与 RD 表中的 ID 匹配(用于连接的字段)。 Status field can have these values: O, C, S.状态字段可以有以下值:O、C、S。

I need to extract (with 2 Select instructions) the list of reservations and the number of reservations for which all products have status 'O'.我需要提取(使用 2 个 Select 指令)预订列表和所有产品状态为“O”的预订数量。

Data example for RP: RP 的数据示例:

ID | RD_ID | ProdID | Status
----------------------------
1  | 1     | 100    | O
2  | 1     | 101    | O
3  | 1     | 102    | O
4  | 2     | 105    | O
5  | 2     | 100    | S
6  | 3     | 101    | C
7  | 3     | 102    | O

In this example, Select statement should return only RD_ID 1在此示例中,Select 语句应仅返回 RD_ID 1

For the number of ID, the following request does not work because it also includes reservations with products having different status:对于 ID 编号,以下请求不起作用,因为它还包括具有不同状态的产品的预订:

SELECT COUNT(rd.ID) FROM rd INNER JOIN rp ON rp.RD_ID = rd.ID WHERE rp.Status = 'O';

Could you help me for the right Select statement?你能帮我正确的 Select 声明吗?

Thank you.谢谢你。

SELECT rd.ID, COUNT(rd.ID) CountOfRD, status FROM rd INNER JOIN rp ON rp.RD_ID GROUP BY rd.ID, status SELECT rd.ID, COUNT(rd.ID) CountOfRD, status FROM rd INNER JOIN rp ON rp.RD_ID GROUP BY rd.ID, status

Use not exists as follows:使用not exists如下:

Select t.* from your_table t
Where t.status = 'O'
  And not exists (select 1 from your_table tt
                   Where t.rd_id = tt.rd_id
                     And t.status != tt.status)

You can also use group by and having as follows:您还可以使用group byhaving如下:

Select rd_id
  From your_table t
Group by rd_id
Having sum(case when status <> 'O' then 1 end) > 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM