0

我正在尝试计算 Encrypted 或 Denied 出现在某个列中的次数。下面的代码返回没有问题

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 会这样做吗?

4

1 回答 1

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
于 2012-05-24T14:49:22.987 回答