引入新列时计算问题

时间:2013-07-31 14:27:10

标签: sql sql-server

SQL的新手。我正在尝试计算有时在两个地区的假期查询中的预订ID总数。

这是我想要的..

ID        count  Region name
427139        1  France
427776        2  Spain
427776        2  France

但似乎只是提供了这个......

ID        count  Region name
427139        1  France
427776        1  Spain
427776        1  France 

预订ID是唯一的,但是当我从Region Region中引入Region时(通过Quotes和Properties表),它会分成2行。

这是我的SQL ..

SELECT count(BO.ID) as Count,
       BO.ID AS 'Booking ID',
       RE.Name AS 'Region name'
FROM Booking BO WITH (NOLOCK)
  LEFT JOIN Quote QU WITH (NOLOCK) ON QU.ID = BO.QuoteID 
  LEFT JOIN Property PR WITH (NOLOCK) ON PR.Code = QU.Code 
  LEFT JOIN Region RE WITH (NOLOCK) ON RE.ID = PR.RegionID 
WHERE BO.ID = '427776' OR BO.ID = '427139'
Group by BO.ID,RE.Name 
ORDER BY BO.ID

有人可以帮忙吗?

感谢您的期待!

2 个答案:

答案 0 :(得分:0)

在SQLServer2005 +中,您可以使用带有聚合函数COUNT()

的OVER()子句
SELECT COUNT(*) OVER(PARTITION BY BO.ID) as [Count],
       BO.ID AS 'Booking ID',
       RE.Name AS 'Region name' 
FROM Booking BO WITH (NOLOCK)
  LEFT JOIN Quote QU WITH (NOLOCK) ON QU.ID = BO.QuoteID 
  LEFT JOIN Property PR WITH (NOLOCK) ON PR.Code = QU.Code 
  LEFT JOIN Region RE WITH (NOLOCK) ON RE.ID = PR.RegionID
WHERE BO.ID = '427776' OR BO.ID = '427139'
GROUP BY BO.ID, RE.Name
ORDER BY BO.ID

我认为新格式的请求可以在没有GROUP BY子句的情况下使用

SELECT COUNT(*) OVER(PARTITION BY BO.ID) as [Count],
       BO.ID AS 'Booking ID',
       RE.Name AS 'Region name' 
FROM Booking BO WITH (NOLOCK)
  LEFT JOIN Quote QU WITH (NOLOCK) ON QU.ID = BO.QuoteID 
  LEFT JOIN Property PR WITH (NOLOCK) ON PR.Code = QU.Code 
  LEFT JOIN Region RE WITH (NOLOCK) ON RE.ID = PR.RegionID
WHERE BO.ID = '427776' OR BO.ID = '427139'
ORDER BY BO.ID

答案 1 :(得分:0)

尝试阅读SQL中的聚合函数(这是我能找到的最佳链接):

http://www.w3resource.com/sql/group-by.php

GROUP BY将结果收集到组中,然后在每个组上调用聚合函数。由于您按ID和区域进行分组,因此您将获得该ID和区域的计数 - 而不是仅针对该ID的计数。

所以这只是选择你想要获得计数的群体。