将两个SQL查询结果合并为一个结果

时间:2015-06-10 08:57:21

标签: sql sql-server sql-server-2008 sql-server-2012

我有如下查询:

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

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

以上查询给出了如下结果:

AppleSupports
63

HpSupports
387

如何让我的查询在一行中获得结果,如下所示?

AppleSupports    HpSupports
63               387

6 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

在select语句中使用子查询:

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

答案 2 :(得分: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

此外,您可以为结果集中的更多列添加值(,如Apple,Hp

答案 3 :(得分: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

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

最简单的方法是:

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