如何在单个查询中获取多列+计数?

时间:2013-12-24 01:46:42

标签: sql sql-server-2008

我通常不会要求“脚本”,而是要求机制,但我认为在这种情况下,如果我看到一个例子,我会理解校长。

我有三张表,如下所示:

enter image description here

我希望从这三个列中获取列数,再加上每个系列中的剧集数量,并得到如下结果:

enter image description here

目前,我正在打开多个数据库线程,我担心随着我在网站上吸引更多访问者,它最终会以非常慢的速度响应。

有什么想法吗?

非常感谢!

4 个答案:

答案 0 :(得分:2)

试试这个:

http://www.sqlfiddle.com/#!3/5f938/17

select min(ec.num) as NumEpisodes,s.Id,S.Name,
       Ep.ID as EpisodeID,Ep.name as EpisodeName,
       C.ID as CreatorID,C.Name as CreatorName
from Episodes ep
join Series s on s.Id=ep.SeriesID
join Creators c on c.Id=s.CreatorID
join (select seriesId,count(*) as Num from Episodes 
      group by seriesId) ec on s.id=ec.seriesID
group by  s.Id,S.Name,Ep.ID,Ep.name,C.ID,C.Name

感谢戈登

答案 1 :(得分:2)

首先将所有表连接在一起以获取列。然后,要获得计数,请使用窗口函数:

SELECT count(*) over (partition by seriesID) as NumEpisodesInSeries,
       st.SeriesId, st.SeriesName, et.episodeID, et.episodeName,
       ct.createdID, ct.CreatorName
FROM series_table st join
     episode_table et
     ON et.ofSeries = st.seriesID join
     creator_table ct
     ON ct.creatorID = st.byCreator;

答案 2 :(得分:2)

按照您的预期在表格及其ID之间进行适当的连接,并加入子查询的结果,该子查询使用“剧集”表确定总集数。

SELECT SeriesCount.NumEpisodes AS #OfEpisodesInSeries, 
    S.id AS SeriesId, 
    S.name AS SeriesName, 
    E.id AS EpisodeId, 
    E.name AS EpisodeName,
    C.id AS CreatorId,
    C.name AS CreatorName
FROM
Series S
INNER JOIN
Episodes E
ON E.seriesId = S.id
INNER JOIN
Creators C
ON S.creatorId = C.id
INNER JOIN
(
    SELECT seriesId, COUNT(id) AS NumEpisodes
    FROM Episodes
    GROUP BY seriesId
) SeriesCount
ON SeriesCount.seriesId = S.id

SQL Fiddle架构:

CREATE TABLE Series (id int, name varchar(20), creatorId int)

INSERT INTO Series VALUES(1, 'Friends', 1)
INSERT INTO Series VALUES(2, 'Family Guy', 2)
INSERT INTO Series VALUES(3, 'The Tonight Show', 1)

CREATE TABLE Episodes (id int, name varchar(20), seriesId int)

INSERT INTO Episodes VALUES(1, 'Joey', 1)
INSERT INTO Episodes VALUES(2, 'Ross', 1)
INSERT INTO Episodes VALUES(3, 'Phoebe', 1)
INSERT INTO Episodes VALUES(4, 'Stewie', 2)
INSERT INTO Episodes VALUES(5, 'Kevin Kostner', 3)
INSERT INTO Episodes VALUES(6, 'Brad Pitt', 3)
INSERT INTO Episodes VALUES(7, 'Tom Hanks', 3)
INSERT INTO Episodes VALUES(8, 'Morgan Freeman', 3)

CREATE TABLE Creators (id int, name varchar(20))

INSERT INTO Creators VALUES(1, 'Some Guy')
INSERT INTO Creators VALUES(2, 'Seth McFarlane')

答案 3 :(得分:1)

我会做以下事情:

SELECT (SELECT Count(*) 
        FROM   episodetbl e1 
        WHERE  e1.ofseries = s.seriesid) AS "#ofEpisodesInSeries", 
       s.seriesid, 
       s.seriesname, 
       e.episodeid, 
       e.episodename, 
       c.creatorid, 
       c.creatorname 
FROM   seriestbl s 
       INNER JOIN creatortbl c 
               ON s.bycreator = c.creatorid 
       INNER JOIN episodetbl e 
               ON e.ofseries = s.seriesid