在嵌套子查询中使用Select Distinct

时间:2014-03-11 20:50:01

标签: sql ms-access-2007

我有一个选择不同的查询,用于标识位置ID(pk)。但我想确定最终用户的位置名称。我以为子查询会返回它。但它返回值1.而不是单独运行select distinct查询时的实际位置ID(25)。似乎无法找出原因。

SELECT Location.LocationID, Location.Location
FROM Location
WHERE (Location.LocationID)=(
    SELECT Count(*) AS UniqueLocations
    FROM (
        SELECT DISTINCT TransactionLocation
        FROM Transactions
        WHERE (Transactions.TransactionActivity) = [Enter Activity] 
         AND (Transactions.TransactionDate) BETWEEN [Enter the start date:] AND [Enter the end date:]
    )
);

交易表

TransactionID(pk)| TransactionEmployee|TransactionActivity|TransactionLocation|Date
1 | 1001 | 1 | 25 | 01/01/2014
2 | 1002 | 1 | 25 | 01/02/2014
3 | 1003 | 1 | 25 | 01/03/2014

位置表

LocationID(pk)|Location Name
24 | Chicago
25 | Pittsburgh
26 | Boston

由于 麦克

1 个答案:

答案 0 :(得分:2)

我想也许你可能想要这样的东西:

SELECT Location.LocationID, Location.Location
FROM Location
WHERE Location.LocationID IN 
  (SELECT DISTINCT TransactionLocation 
   FROM Transactions
   WHERE Transactions.TransactionActivity = [Enter Activity] 
   AND Transactions.TransactionDate Between [Enter the start date:] And [Enter the end date:]);