如何将两个值(行)组合成一个具有自定义值的行?

时间:2015-04-22 10:20:28

标签: sql sql-server database sql-server-2008

所以我有这个样本表。包含所有互联网商店分支机构OS的安装数据。

ID   ShopName   PCName   OS
1    Mineski    M101     WinXP
2    Mineski    M102     WinXP
3    GameCity   G201     Win7
4    GameCity   G202     Win7
5    CyberBob   C301     WinXP
6    CyberBob   C302     Win7

我需要查询Shop安装的OS

我可以使用此查询执行此操作。

select ShopName, OS
from ShopInv
group by ShopName, OS

预期结果将是:

ShopName    OS
CyberBob    Win7
CyberBob    WinXP
GameCity    Win7
Mineski     WinXP

但是,我只希望列出每个商店1行。因此,如果有超过1行(由于安装了不同的OS版本),就像上面的示例一样。我只是想显示混合

所以结果会是这样的:

ShopName    OS
CyberBob    Mixed
GameCity    Win7
Mineski     WinXP

这在SQL Server 2008上是否可行?

SQLFiddle

注意:我对如何陈述我的问题有点困惑,所以如果你愿意,请编辑它。 :)

4 个答案:

答案 0 :(得分:6)

对于每次case检查,您可以使用distinct OS countShopName

select ShopName
     , case when count(distinct OS) > 1 then 'Mixed' else min(OS) end
from ShopInv
group by ShopName

SQLFiddle

答案 1 :(得分:4)

这很简单:因为您希望每个商店有一排,所以只能按店铺分组。然后使用聚合函数获取操作系统。这可以是MIN或MAX。但是,如果您检测到,那么MIN<> MAX,然后你必须显示'混合'代替。

select 
  ShopName,
  case when MIN(OS) = MAX(OS) then MIN(OS) else 'Mixed' end as OS
from ShopInv
group by ShopName;

答案 2 :(得分:2)

如前所述,我已经给出了预期的输出

 declare @t table (Id int,Shop varchar(10),PCname varchar(10),OS Varchar(10))

    insert into @t (Id,Shop,PCname,os)values (1,'Mineski','M101','WinXP'),
    (2,'Mineski','M102','WinXP'),(3,'GameCity','G201','Win7'),
    (4,'GameCity','G202','Win7'),(5,'CyberBob','C301','WinXP'),
    (6,'CyberBob','C302','Win7')

第一个结果

;with cte as (
select shop,OS,ROW_NUMBER()OVER(PARTITION BY shop,OS ORDER BY shop ) rn from @t)
select shop,OS from cte
where rn = 1

最终结果集

;with cte as (
select shop,OS,ROW_NUMBER()OVER(PARTITION BY shop,OS ORDER BY shop ) rn from @t)
,CTE2 AS (
Select shop,CASE WHEN R = 1 THEN 'MIXED' ELSE OS END AS 'OS' from (
select shop,OS,count(rn)R from cte
group by Shop,OS )S )
select DISTINCT shop,OS from CTE2

答案 3 :(得分:0)

select Shopname,
(select case when count(shopname)>1 then 'Mixed' 
         else OS 
         from ShopInv b
         where a.shopname=b.shopname
         group by b.shopname)
from ShopInv a