单个查询返回单个记录中不同 ID 的计数

Bij*_*ose 3 sql-server query select

select count(title_id)as algodata from titles where pub_id =1389  
select count(title_id)as binnet   from titles where pub_id =0877  
select count(title_id)as newmoon  from titles where pub_id =0736
Run Code Online (Sandbox Code Playgroud)

使用的数据库pubs在 SQL Server 中。

我可以使用单个查询来显示单个记录中每个发布者(这里有 3 个发布者)的记录数吗?

gbn*_*gbn 9

与@ypercubes 类似,但在没有 3 个单独查询的情况下获得一行

select
     count(CASE WHEN pub_id = '1389' THEN title_id END) as algodata,
     count(CASE WHEN pub_id = '0877' THEN title_id END) as binnet,   
     count(CASE WHEN pub_id = '0736' THEN title_id END) as newmoon  
from titles
where pub_id IN ('1389', '0877', '0736') 
Run Code Online (Sandbox Code Playgroud)

此外,确定您的值是数字还是字符串并保持一致以避免数据类型转换


Mar*_*ith 7

您也可以使用Pivot假设您至少使用 SQL Server 2005

SELECT [1389] AS algodata,
       [0877] AS binnet,
       [0736] AS newmoon
FROM   titles PIVOT (COUNT(title_id) FOR pub_id IN ([1389], [0877], [0736])) P 
Run Code Online (Sandbox Code Playgroud)


ype*_*eᵀᴹ 6

结果为 3 行:

SELECT pub_id 
     , COUNT(title_id) AS algodata 
FROM titles 
WHERE pub_id IN (1389, 877, 736)  
GROUP BY pub_id ;
Run Code Online (Sandbox Code Playgroud)

要在一行中获取结果:

SELECT 
  ( select count(title_id) as algodata from titles where pub_id = 1389 ) AS algodata,
  ( select count(title_id) as binnet   from titles where pub_id = 0877 ) AS binnet,
  ( select count(title_id) as newmoon  from titles where pub_id = 0736 ) AS newmoon;
Run Code Online (Sandbox Code Playgroud)