3

给定下表:

已安装的应用程序

MachineName | AppName | Version
-------------------------------
machine01   | App01   | 1.1
machine01   | App02   | 1.0
machine01   | App03   | 1.5
machine02   | App04   | 2.0
machine02   | App02   | 1.0
machine02   | App01   | 1.1
machine03   | App06   | 7.9.9
machine03   | App01   | 1.1
machine03   | App07   | 11.5
machine03   | App02   | 1.0

我需要选择Apps给定的“n”台机器所共有的。它是“n”个集合之间的交集。但是,我很难提出一个体面的查询。

我知道我可以做这样的事情:

SELECT AppName, Version 
FROM InstalledApps 
WHERE MachineName = 'machine01'

INTERSECT

SELECT AppName, Version 
FROM InstalledApps 
WHERE MachineName = 'machine02' 

那会给我

AppName | Version
------------------
App01   | 1.1
App02   | 1.0

但是,有没有一种方法可以做到,而无需预先知道机器的数量?就像是

SELECT...... 
FROM InstalledApps 
WHERE MachineName IN ('machine01',...'machine99')
4

4 回答 4

4

我认为这应该适用于一般情况:

SELECT AppName, Version, COUNT(DISTINCT(MachineName)) AS MachineCount
FROM InstalledApps
GROUP BY
  AppName, Version
HAVING
  COUNT(DISTINCT(MachineName)) > 1
于 2012-05-30T14:20:13.743 回答
1

您可以使用Row_Number函数和Partition带有机器名称的数据

Select AppName, [Version] From 
(
    Select Row_Number() Over(Partition By MachineName Order by AppName) RowId, * 
    From InstalledApps
)K
Where K.RowId = 2
于 2012-05-30T16:41:53.967 回答
0

您可以通过 group by 执行此操作。假设 InstalledApps 表中的给定应用没有重复的机器:

select apps
from InstalledApps
group by apps
having sum(case when machine in (<list of machines>) then 1 else 0 end) = <number of machines>

如果您的机器上有重复的应用程序:

select apps
from (select distinct apps, machine from InstalledApps) ia
group by apps
having sum(case when machine in (<list of machines>) then 1 else 0 end) = <number of machines>

而且,我在想​​,如果您不想计算机器数量,那么您可能需要使用动态 SQL 或将机器名称存储在临时表中。

于 2012-05-30T19:45:17.463 回答
0

您可以参数化 IN 查询

Declare @value varchar(max)
Declare @sql varchar(max)
select @value = 'machine1,machine2,machine3'
SELECT @sql = 'SELECT * FROM InstalledApps  WHERE MachineName in (' + @value+ ')'

 exec sp_executeSQL @sql 

或者您甚至可以使用子查询来获取所有值

SELECT * FROM InstalledApps WHERE MachineName in (SELECT MachineName FROM InstalledApps    group by MachineName HAVING COUNT(DISTINCT(MachineName)) > 1)
于 2012-05-30T14:21:32.837 回答