我不知道我的标题是正确的,但让我解释一下我在寻找什么。
我有两张桌子。
用户评分
maxContourarea
游戏
user (primary key)
game (varchar)
score (int)
客户用户评分数据如下所示
game (varchar)
游戏表数据如下所示
user game score
Chris naruto 10
Gale dungen 9
Donna winning eleven 8
是否可以创建如下所示的视图:
game
dungen
naruto
winning eleven
提前致谢。
答案 0 :(得分:2)
您首先需要使用交叉联接获取用户+游戏的所有可能组合的一组不同的组合:
select distinct u.user, g.game
from game g
cross join user u
;
这将给出以下结果:
| USER | game |
|-------|----------------|
| Chris | dungen |
| Chris | naruto |
| Chris | winning eleven |
| Gale | dungen |
| Gale | naruto |
| Gale | winning eleven |
| Donna | dungen |
| Donna | naruto |
| Donna | winning eleven |
然后您可以通过这种方式将此结果集(使用外部联接)加入user
表:
SELECT *
FROM (
select distinct u.user, g.game
from game g
cross join user u
) x
LEFT JOIN user u ON x.user = u.user and x.game = u.game
;
以上查询为您提供以下结果集:
| user | game | USER | game | score |
|-------|----------------|--------|----------------|--------|
| Chris | naruto | Chris | naruto | 10 |
| Gale | dungen | Gale | dungen | 9 |
| Donna | winning eleven | Donna | winning eleven | 8 |
| Chris | dungen | (null) | (null) | (null) |
| Chris | winning eleven | (null) | (null) | (null) |
| Gale | naruto | (null) | (null) | (null) |
| Gale | winning eleven | (null) | (null) | (null) |
| Donna | dungen | (null) | (null) | (null) |
| Donna | naruto | (null) | (null) | (null) |
接下来,您可以使用上述结果集使用简单的SUM和GROUB BY生成报告 但首先你需要用0替换所有空值,因为空值之和给出空值 这样:
SELECT x.user, x.game,
sum( case when score is not null then score else 0 end ) as score
FROM (
select distinct u.user, g.game
from game g
cross join user u
) x
LEFT JOIN user u ON x.user = u.user and x.game = u.game
GROUP BY x.user, x.game
order by x.user, x.game
;
此查询产生以下内容:
| user | game | score |
|-------|----------------|-------|
| Chris | dungen | 0 |
| Chris | naruto | 10 |
| Chris | winning eleven | 0 |
| Donna | dungen | 0 |
| Donna | naruto | 0 |
| Donna | winning eleven | 8 |
| Gale | dungen | 9 |
| Gale | naruto | 0 |
| Gale | winning eleven | 0 |
您可以在此处找到完整的可运行示例:http://sqlfiddle.com/#!9/657cdf/12
我在这些示例中使用SQL的MySql方言,因为它在SqlFiddle上可用
但我相信将其转换为MS-Access应该不是问题。
我在MS-Access 2010上测试了这个查询 MS-Access不支持两件事:
MS Access不支持CROSS JOIN
个关键字
它可以通过以下方式转换:How to use cross join in access?
在表格之间使用“旧”语法和逗号:
SELECT DISTINCT u.user, g.game
FROM game g, user u
MS-Access不支持案例表达式
:
CASE WHEN condition THEN value1 ELSE value2 END
但你可以改用IIF功能:
IIF( condition, value1, value2 )
更多相关信息:Does MS Access support "CASE WHEN" clause if connect with ODBC?
整个查询转换为MS-Access方言:
SELECT x.user, x.game,
sum( IIF( u.score IS NOT NULL, u.score, 0)) as score
FROM (
SELECT DISTINCT u.user, g.game
FROM game g, user u
) x
LEFT JOIN user u ON x.user = u.user and x.game = u.game
GROUP BY x.user, x.game
ORDER BY x.user, x.game