【问题标题】:Merge two SQL query results into one result将两个 SQL 查询结果合并为一个结果
【发布时间】:2015-06-10 08:57:20
【问题描述】:
我有如下查询:
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
【问题讨论】:
标签:
sql
sql-server
sql-server-2008
sql-server-2012
【解决方案1】:
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')
【解决方案2】:
在你的选择语句中使用子查询:
SELECT
(select count(*) from VendorItemPricing where VendorName = 'Apple') as AppleSupports,
(select count(*) from VendorItemPricing where VendorName = 'HP') AS HpSupports
【解决方案3】:
理想情况下你应该这样做,
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)
【解决方案4】:
试试这个。
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
【解决方案5】:
它需要一个简单的查询连接。试试这个:
select * from
(select count(*) as AppleSupports from VendorItemPricing where VendorName = 'Apple'),
(select count(*) as HpSupports from VendorItemPricing where VendorName = 'HP')
【解决方案6】:
最简单的方法是:
SELECT
COUNT(CASE WHEN VendorName = 'Apple' Then 1 End) As AppleSupports,
COUNT(CASE WHEN VendorName = 'HP' THEN 1 End) As HpSupports
FROM
VendorItemPricing