【发布时间】:2012-12-28 08:23:20
【问题描述】:
我有这张桌子:
idSection | idQuestion | title | enunciation | idScale
1 | 1 | title 1 | question 1 | 3
1 | 1 | title 1 | question 1 | 3
1 | 1 | title 1 | question 1 | 3
1 | 1 | title 1 | question 1 | 2
1 | 1 | title 1 | question 1 | 5
1 | 2 | title 2 | question 2 | 1
1 | 2 | title 2 | question 2 | 3
1 | 3 | title 3 | question 3 | 1
还有这张桌子:
idScale | name
1 | Very Bad
2 | Bad
3 | Good
4 | Very Good
5 | Excellent
我想要一张这样的桌子:
idSection | idQuestion | title | enunciation | Total | Name
1 | 1 | title 1 | question 1 | 0 | Very Bad
1 | 1 | title 1 | question 1 | 0 | Bad
1 | 1 | title 1 | question 1 | 3 | Good
1 | 1 | title 1 | question 1 | 0 | Very Good
1 | 1 | title 1 | question 1 | 1 | Excellent
1 | 2 | title 2 | question 2 | 0 | Very Bad
1 | 2 | title 2 | question 2 | 1 | Bad
1 | 2 | title 2 | question 2 | 3 | Good
1 | 2 | title 2 | question 2 | 0 | Very Good
1 | 2 | title 2 | question 2 | 0 | Excellent
查询:
SELECT
t1.idSection, t1.idQuestion, t1.title, t1.enunciation,
COUNT(t1.idScale) as Total, t2.name
FROM
table1 AS t1
INNER JOIN
table2 as t2 ON t2.idScale = t1.idScale
GROUP BY
t1.idSection, t1.idQuestion, t1.title, t1.enunciation, t2.name
这样的结果是查询:
idSection | idQuestion | title | enunciation | Total | Name
1 | 1 | title 1 | question 1 | 3 | Good
1 | 1 | title 1 | question 1 | 1 | Excellent
1 | 2 | title 2 | question 2 | 1 | Bad
1 | 2 | title 2 | question 2 | 3 | Good
这样的问题是查询值为0的不会出现。
【问题讨论】:
-
idEscalaEntrada 字段从何而来?
-
@Bulat 抱歉复制粘贴问题...是 idScale...我编辑...
-
您是否尝试过使用
RIGHT JOIN而不是INNER JOIN? -
我什至会说 LEFT JOIN
-
您的第二个表没有 0,因此 0 不会出现在选择中。添加 0 或使用外部(左、右)连接
标签: sql sql-server join inner-join