将两个SQL查询结果合并为一个结果
我有如下疑问:将两个SQL查询结果合并为一个结果,sql,sql-server,sql-server-2008,sql-server-2012,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 以上查询给我的结果如下: SELECT COUNT(*) AS AppleSuppo
SELECT COUNT(*) AS AppleSupports
FROM VendorItemPricing
WHERE VendorName = 'Apple'
SELECT COUNT(*) AS HpSupports
FROM VendorItemPricing
WHERE VendorName = 'HP'
AppleSupports
63
HpSupports
387
以上查询给我的结果如下:
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
在select语句中使用子查询:
SELECT
(select count(*) from VendorItemPricing where VendorName = 'Apple') as AppleSupports,
(select count(*) from VendorItemPricing where VendorName = 'HP') AS HpSupports
理想情况下,你应该这样做
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)试试这个
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')
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
这需要一个简单的查询联接。试试这个:
select * from
(select count(*) as AppleSupports from VendorItemPricing where VendorName = 'Apple'),
(select count(*) as HpSupports from VendorItemPricing where VendorName = 'HP')
最简单的方法是:
SELECT
COUNT(CASE WHEN VendorName = 'Apple' Then 1 End) As AppleSupports,
COUNT(CASE WHEN VendorName = 'HP' THEN 1 End) As HpSupports
FROM
VendorItemPricing