使用内连接时,SQL查询返回膨胀计数

时间:2012-05-24 14:46:00

标签: sql sql-server

我正在尝试计算某列中加密或拒绝的次数。下面的代码返回没有问题的代码

use DEW
SELECT Count (distinct DeviceData.machinename) As [Number Of Devices], 
DeviceData.CurrentSite, DeviceData.Country
  ,sum(case buildstatus when 'encrypted' then 1 else 0 end) encrypted
  ,sum(case buildstatus when 'Denied' then 1 else 0 end) Denied
FROM dbo.DeviceData
where currentsite = 'REN'
group by DeviceData.Country, CurrentSite

输出是这样的:

Number of Devices SiteCode Country Encrypted Denied
       3             REN    Greece    0         3

但是当我添加内连接时

FROM dbo.DeviceData JOIN dbo.SiteList ON dbo.DeviceData.country = dbo.SiteList.Country

拒绝更改为33的数量。

知道为什么SQL会这样做吗?

1 个答案:

答案 0 :(得分:3)

我想在SiteList表中有11个希腊站点。因此,结果如预期。

如果您执行了以下操作:

SELECT 
    DeviceData.machinename,
    SiteList.Country,
    SiteList.Site, -- Or whatever the column is called...
FROM dbo.DeviceData JOIN 
     dbo.SiteList ON 
         dbo.DeviceData.country = dbo.SiteList.Country

您将看到返回33行:

MACHINENAME    COUNTRY    SITE
Machine#1      Greece     Site1
Machine#1      Greece     Site2
Machine#1      Greece     Site3
Machine#1      Greece     Site4
Machine#1      Greece     Site5
Machine#1      Greece     Site6
Machine#1      Greece     Site7
Machine#1      Greece     Site8
Machine#1      Greece     Site9
Machine#1      Greece     Site10
Machine#1      Greece     Site11
Machine#2      Greece     Site1
Machine#2      Greece     Site2
Machine#2      Greece     Site3
Machine#2      Greece     Site4
etc...

我认为您需要的修复是加入Site,而不是Country

 FROM dbo.DeviceData JOIN 
      dbo.SiteList ON 
           dbo.DeviceData.CurrentSite = dbo.SiteList.Site