如何使用这两列来获取第三列的结果

时间:2017-08-01 09:02:17

标签: mysql sql two-columns

我有这个SQL查询

SELECT
  SERVERPROPERTY('MachineName') AS FoodServer,
  SUM(Extended * Multiplier) AS GrossSale,
  (SELECT
    COUNT(*)
  FROM FinishedTransaction)
  AS counts
FROM finishedsales fs
LEFT JOIN FinishedTransaction ft
  ON fs.TransactionNo = ft.TransactionNo

现在,我希望获得GrossSale列的商数并计算列并将其显示到第三列。我在下面尝试了此查询,但它无效..

SELECT
  SERVERPROPERTY('MachineName') AS FoodServer,
  SUM(Extended * Multiplier) AS GrossSale,
  (SELECT
    COUNT(*)
  FROM FinishedTransaction)
  AS counts,
  (GrossSale / counts) AS result
FROM finishedsales fs
LEFT JOIN FinishedTransaction ft
  ON fs.TransactionNo = ft.TransactionNo

这个替代解决方案正在运作..

SELECT
  SERVERPROPERTY('MachineName') AS FoodServer,
  SUM(Extended * Multiplier) AS GrossSale,
  (SELECT
    COUNT(*)
  FROM FinishedTransaction)
  AS counts,
  SUM(Extended * Multiplier) / (SELECT
    COUNT(*)
  FROM FinishedTransaction)
  AS result
FROM finishedsales fs
LEFT JOIN FinishedTransaction ft
  ON fs.TransactionNo = ft.TransactionNo

但我不想要那个解决方案,因为它有点罗嗦,表现不佳。我想知道这个问题的最佳解决方案

1 个答案:

答案 0 :(得分:4)

我认为你的解决方案没有任何问题,你可能会更喜欢这个,但我怀疑你会有更好的表现。

Select Foodserver, GrossSale, Counts, (GrossSale / counts) as result    
    FROM
    (
        SELECT SERVERPROPERTY ('MachineName') as FoodServer,
        SUM(Extended * Multiplier) as GrossSale, 
        (SELECT COUNT(*) FROM FinishedTransaction) as counts

        FROM finishedsales fs LEFT JOIN FinishedTransaction ft
        ON fs.TransactionNo = ft.TransactionNo
    ) as salesData

NB。你应该在这里添加除以零检查。我认为where GrossSale <>0 AND Counts <>0应该这样做。