复杂的SQL查询

时间:2012-08-26 16:35:46

标签: sql

有没有人知道如何构建以下查询:

表格:

TBL_GAME                 id,      name
TBL_CATEGORY             id,      name
LU_GAME_TO_CATEGORY      gameid,  catid
LU_GAME_TO_EVENT         eventid, gameid

所以,基本上Categories有很多游戏。

Events有很多游戏。

我想生成一个报告,显示Categories列出的GamesEvents中使用了多少{{1}}。按数量下降订购。

这可能吗?

2 个答案:

答案 0 :(得分:2)

SELECT
       c.id                 as catId,
       c.name               as catName,
       g.id                 as gameId,
       g.name               as gameName,
       sum(ge.INT_QUANTITY) as totalQuantities
FROM
       TBL_CATEGORY         as c,
       TBL_GAME             as g,
       LU_GAME_TO_CATEGORY  as gc,
       LU_GAME_TO_EVENT     as ge
WHERE
       c.id = gc.catId     AND
       g.id = gc.gameId    AND
       g.id = ge.gameId
GROUP BY
       c.id,
       g.id
ORDER BY
       totalQuantities desc,
       c.name,
       g.name

答案 1 :(得分:1)

SELECT A.ID, SUM(D.INT_QUANTITY) AS YourSum
FROM TBL_CATEGORY A --Adapt your selected columns 
INNER JOIN LU_GAME_TO_CATEGORY B ON A.id = B.catid
INNER JOIN TBL_CATEGORY C ON B.gameid = C.id
INNER JOIN LU_GAME_TO_EVENT  D ON C.gameid = D.gameid
GROUP BY A.ID
ORDER BY YourSum DESC;

此处我不会调整金额,因为列不存在。 您必须在目标表

中添加金额列