2015-06-10 246 views
2

我有查询象下面这样:合并两个SQL查询结果为一个结果

SELECT COUNT(*) AS AppleSupports 
FROM VendorItemPricing 
WHERE VendorName = 'Apple' 

SELECT COUNT(*) AS HpSupports 
FROM VendorItemPricing 
WHERE VendorName = 'HP' 

上面的查询给我结果如下图所示:

AppleSupports 
63 

HpSupports 
387 

怎样才能让我的查询来获取一行结果像下面一样?你的SELECT语句里面

AppleSupports HpSupports 
63    387 

回答

0

使用子查询:

SELECT 
(select count(*) from VendorItemPricing where VendorName = 'Apple') as AppleSupports, 
(select count(*) from VendorItemPricing where VendorName = 'HP') AS HpSupports 
0

理想情况下,你应该这样做,

select [Apple] as AppleSupport, [Hp] as HpSupport from (
    select VendorName from VendorItemPricing 
) as sourcetable 
pivot 
(count(VendorName) 
for VendorName in ([Apple],[Hp]) 
) as pivottable 

而且你可以添加值(像苹果,惠普)为结果集中的更多列

3
Select Sum(Case When vp.VendorName = 'Apple' Then 1 Else 0 End) As AppleSupports 
     ,Sum(Case When vp.VendorName = 'HP' Then 1 Else 0 End) As HpSupports 
From VendorItemPricing As vp With (Nolock) 
Where vp.VendorName In ('Apple','HP') 
0

试试这个。

SELECT SUM(AppleSupports) AS AppleSupports, SUM(HpSupports) AS HpSupports 
FROM 
(
    SELECT CASE WHEN VendorName = 'Apple' 
       THEN COUNT(*) END AS AppleSupports, 
      CASE WHEN VendorName = 'HP' 
       THEN COUNT(*) END AS HpSupports 
    FROM VendorItemPricing 
    GROUP BY VendorName 
) AS A 
0

它需要查询的简单连接。试试这个:

select * from 
(select count(*) as AppleSupports from VendorItemPricing where VendorName = 'Apple'), 
(select count(*) as HpSupports from VendorItemPricing where VendorName = 'HP') 
0

简单的方法是:

SELECT 
    COUNT(CASE WHEN VendorName = 'Apple' Then 1 End) As AppleSupports, 
    COUNT(CASE WHEN VendorName = 'HP' THEN 1 End) As HpSupports 
FROM 
    VendorItemPricing 
相关问题