代码之家  ›  专栏  ›  技术社区  ›  Nathan

如何在SQL中引用自定义字段

  •  4
  • Nathan  · 技术社区  · 18 年前

    select 
      customerName, 
      customerId,
      (
        select count(*) 
        from Purchases 
        where Purchases.customerId=customerData.customerId
      ) as numberTransactions
    from customerData
    

    order by numberTransactions
    

    它告诉我没有这样的领域。有可能这样做吗?我是否应该使用某种特殊的关键字,例如 this 或 self ?

    7 回复  |  直到 18 年前
        1
  •  8
  •   Jonathan Rupp    18 年前

    使用字段编号,在这种情况下:

    order by 3
    
        2
  •  7
  •   Amy B    18 年前

    有时,您必须与SQL的语法(预期的子句范围)搏斗

    SELECT *
    FROM
    (
    select
      customerName,
      customerId,
      (
        select count(*)
        from Purchases
        where Purchases.customerId=customerData.customerId
      ) as numberTransactions
    from customerData
    ) as sub
    order by sub.numberTransactions
    

    此外,使用JOIN的解决方案也是正确的。看看查询计划,SQL Server应该为这两个解决方案提供相同的计划。

        3
  •  4
  •   Indeed is Trash    18 年前

    做一个内部连接。它更容易阅读。

    select 
    customerName,
    customerID,
    count(*) as numberTransactions
    from
        customerdata c inner join purchases p on c.customerID = p.customerID
    group by customerName,customerID
    order by numberTransactions
    
    

    你知道你可以将整个表作为一个子表连接起来吗?

    Select T.*, T2.*
    From T inner join 
    (select 
    customerName,
    customerID,
    count(*) as numberTransactions
    from
        customerdata c inner join purchases p on c.customerID = p.customerID
    group by customerName,customerID
    ) T2 on T.CustomerID = T2.CustomerID
    order by T2.numberTransactions
    

        4
  •  2
  •   MotoWilliams    18 年前

    有更好的方法可以获得结果,但仅从您的示例查询中,这将适用于SQL2000或更高版本。

    如果您将别名包装为单个记号 然后打电话 按“编号交易”排序

    select
      customerName, 
      customerId,
      (
        select count(*) 
        from Purchases 
        where Purchases.customerId=customerData.customerId
      ) as 'numberTransactions'
    from customerData
    ORDER BY 'numberTransactions'
    
        5
  •  0
  •   Thomas    18 年前

    同样的事情也可以通过使用 GROUP BY JOIN ,您将摆脱子查询。这也可能更快。

        6
  •  0
  •   John Sheehan    18 年前

    我认为您可以在SQL2005中实现这一点,但不能在SQL2000中实现。

        7
  •  -1
  •   theo    18 年前

    你需要复制你的逻辑。SQL Server对于已命名但不是FROM语句中数据集一部分的列不是很智能。

    所以使用

    select 
      customerName, 
      customerId,
      (
        select count(*) 
        from Purchases p
        where p.customerId = c.customerId
      ) as numberTransactions
    from customerData c
    order by (select count(*) from purchases p where p.customerID = c.customerid)
    

    此外,使用别名,可以使代码更易于阅读和维护。;)