在嵌套的SELECTS中使用COUNT

时间:2015-09-24 17:50:24

标签: sql sql-server count

我正在尝试计算列中值的实例数,并将其返回到另一列。我已成功完成了硬编码值的计算,但无法弄清楚如何从主SELECT中获取变量到COUNT。

在底部的示例数据中,CommissionRate显示该行中的DealInstanceOID值显示在DealInstanceOID列中的次数。我的硬编码解决方案适用于所有这些值,但动态发生这种情况令我感到困惑。 DealInstanceOID变量超出了嵌套SELECT的范围,我不确定如何解决这个问题。

我之前发布了这个问题并且对我的表格如何加入有一些抱怨 - 无法从这些海报中获得更多反馈,而是按照他们的建议重新发布。

SELECT
D.DealOID
DD.DealInstanceOID
, CommissionRate = (SELECT (DealInstanceOID COUNT(*) FROM dbo.DealDetail WHERE DealInstanceOID = 4530))
, Commission = CONVERT(MONEY,C.Commission,1)

FROM dbo.Book AS B WITH(NOLOCK)
INNER JOIN Contract as C WITH(NOLOCK) ON B.BookOID = C.BookOID
INNER JOIN Deal as D WITH(NOLOCK)ON C.ContractOID = D.ContractOID
INNER JOIN DealInstance DI WITH(NOLOCK) ON DI.DealOID = D.DealOID
INNER JOIN DealDetail AS DD WITH(NOLOCK)ON DD.DealInstanceOID = DI.DealInstanceOID

GROUP BY
DD.DealInstanceOID
, D.DealOID 
, C.Commission
, B.BookOID

ORDER BY DealOID ASC


DealOID |Commission |CommissionRate|Commission/Rate|DealInstanceOID
101     |  $1000    |       5      |     $200.00   |     4530
101     |  $1000    |       5      |     $200.00   |     4530
101     |  $1000    |       5      |     $200.00   |     4530
101     |  $1000    |       5      |     $200.00   |     4530
101     |  $1000    |       5      |     $200.00   |     4530
101     |  $5000    |       6      |     $833.33   |     4531
102     |  $5000    |       6      |     $833.33   |     4531
102     |  $5000    |       6      |     $833.33   |     4531
102     |  $5000    |       6      |     $833.33   |     4531
102     |  $5000    |       6      |     $833.33   |     4531
102     |  $5000    |       6      |     $833.33   |     4531
103     |  $6000    |       3      |     $2,000.00 |     4540
103     |  $6000    |       3      |     $2,000.00 |     4540
103     |  $6000    |       3      |     $2,000.00 |     4540

3 个答案:

答案 0 :(得分:1)

您应该能够通过表别名和列名称来引用它:

...
 WHERE dbo.DealDetail.DealInstanceOID = DD.DealInstanceOID))
...

答案 1 :(得分:1)

标量子选择语句有两个问题。一个是语法错误,另一个是引用。修复它们如下:

CommissionRate = (SELECT COUNT(*) FROM dbo.DealDetail as s WHERE s.DealInstanceOID = dd.DealInstanceOID)

答案 2 :(得分:1)

对每一行使用连接而不是选择。

关键是使用CTE。正如您在下面看到的,结果是针对数据库的两个选择,而不是每行的一个选择。

WITH counts AS
(  -- This will give a virtual table (CTE) with ID and count
   SELECT DealInstanceOID, COUNT(*) as C
   FROM dbo.DealDetail
   GROUP BY DealInstanceOID
)
SELECT
  D.DealOID,
  DI.DealInstanceOID,
  counts.C AS CommissionRate,
  CONVERT(MONEY,C.Commission,1) AS Commission 
FROM dbo.Book AS B WITH(NOLOCK)
JOIN Contract as C WITH(NOLOCK) ON B.BookOID = C.BookOID
JOIN Deal as D WITH(NOLOCK)ON C.ContractOID = D.ContractOID
JOIN DealInstance DI WITH(NOLOCK) ON DI.DealOID = D.DealOID
JOIN counts ON DI.DealInstanceOID = counts.DealInstanceOID
GROUP BY DI.DealInstanceOID, D.DealOID, C.Commission, B.BookOID
ORDER BY DealOID ASC