是否可以在select语句中包含子查询?

时间:2017-08-29 17:21:18

标签: sql ms-access

我有以下三个表:

dbo_CURRENCYRATES
+-------------+---------+---------------+
|CURRENCY_ID  |BUY_RATE |DATE_EFFECTIVE |
+-------------+---------+---------------+
|GBP          |1.5      |01/01/2000     |
|USD          |2.5      |01/01/2000     |
|EUR          |0.5      |01/01/2000     |
|GBP          |1.7      |01/01/2017     |
|USD          |2.7      |01/01/2017     |
|EUR          |0.7      |01/01/2017     |
+-------------+---------+---------------+

dbo_DISCOUNTRATES
+-------------+--------------+
|DISCOUNT     |DISCOUNT_RATE |
+-------------+--------------+
|50           |0.5           |
|25           |0.25          |
|35           |0.35          |
+-------------+--------------+

dbo_CUSTOMER
+-------+---------------+---------+----------+
|ID     |NAME           |CURRENCY | DISCOUNT |
+-------+---------------+---------+----------+
|1      |Widgets INC    |USD      |50        |
|2      |Widgets GMBH   |EUR      |35        |
|3      |Widgets PLC    |GBP      |25        |
+-------+---------------+---------+----------+

和查询

CurrentExchangeRate
+--------------------------------------------+
SELECT 
   a.CURRENCY_ID
  ,a.BUY_RATE
FROM dbo_CURRENCYRATES AS t 
   INNER JOIN 
      (
       SELECT 
          CURRENCY_ID
         ,MAX(DATE_EFFECTIVE) AS MaxDate 
       FROM dbo_CURRENCYRATES 
       GROUP BY dbo_CURRENCYRATES.CURRENCY_ID
      ) AS tm 
          ON (a.CURRENCY_ID = b.CURRENCY_ID) 
          AND (a.DATE_EFFECTIVE = b.MaxDate);

我有一个选择查询,它从dbo_CUSTOMER中选择包含货币和折扣的数据。

SELECT 
   dbo_CUSTOMER.ID
  ,dbo_CUSTOMER.NAME
  ,dbo_CUSTOMER.CURRENCY_ID AS [CURRENCY]
  ,BUY_RATE
  ,dbo_CUSTOMER.DISCOUNT
  ,DISCOUNT_RATE
FROM dbo_CUSTOMER
WHERE ID = '1';

是否可以在此查询中包含一个子查询,它允许我通过查询另一个表来获取货币的BUY_RATE(来自单独的查询)和适当的折扣率?

我有一个单独的查询来获取货币汇率,因为我需要获得特定货币的最新价值。

所以,在伪代码中,我可以这样做:

SELECT 
   dbo_CUSTOMER.ID
  ,dbo_CUSTOMER.NAME
  ,dbo_CUSTOMER.CURRENCY_ID AS [CURRENCY]
  ,dbo_CUSTOMER.DISCOUNT
  ,(
    SELECT BUY_RATE 
    FROM CurrentExchangeRate 
    WHERE CurrentExchangeRate.CURRENCY_ID = [CURRENCY]
   ) as BUY_RATE
  ,(
    SELECT DISCOUNT_RATE 
    FROM dbo_DISCOUNTRATES 
    WHERE dbo_DISCOUNTRATES.DISCOUNT = dbo_CUSTOMER.DISCOUNT
   ) as DISCOUNT_RATE
FROM dbo_CUSTOMER
WHERE ID = '1';

是否可以这样做,首先是在查询中,其次是在访问数据库中?

由于

1 个答案:

答案 0 :(得分:1)

是的,你可以。只需要在子查询中提示,根据需要,您需要在日期字段中选择TOP 1和ORDER BY DESC。