使用WHERE子句连接多个表

时间:2015-01-23 20:44:12

标签: sql sqlite

我有一个主表(项目列表)以及在一个公共字段(RecNum)上连接的几个子表。我需要按列列出所有子表的总计,我不知道该怎么做。这是表格设计的一个示例。每个表格中有更多列,但我会显示列名称和值的示例,以了解要执行的操作。

Project List
| RecNum |
|      6 |

WeekA
| RecNum | UserName | Day1Reg | Day1OT | Day2Reg | Day2OT | Day3Reg | Day3OT |
|      6 | JustMe   |       1 |      2 |       3 |      4 |       5 |      6 |
|      6 | NotMe    |       1 |      2 |       3 |      4 |       5 |      6 |

WeekB
| RecNum | UserName | Day1Reg | Day1OT | Day2Reg | Day2OT | Day3Reg | Day3OT |
|      6 | JustMe   |       7 |      8 |       1 |      2 |       3 |      4 |
|      6 | NotMe    |       7 |      8 |       1 |      2 |       3 |      4 |

因此,第一个查询应返回两个用户的完整总计,如下所示:

| sumDay1Reg | sumDay1OT | sumDay2Reg | sumDay2OT | sumDay3Reg | sumDay3OT |
|         16 |        20 |          8 |        12 |         16 |        20 |

第二个查询应该返回指定用户的总数(WHERE UserName =' JustMe'),如下所示:

| sumDay1Reg | sumDay1OT | sumDay2Reg | sumDay2OT | sumDay3Reg | sumDay3OT |
|          8 |        10 |          4 |         6 |          8 |        10 |

2 个答案:

答案 0 :(得分:1)

拥有存储相同类型数据的多个表是一个坏主意;你应该有一个Weeks表,它有一周的附加列。

无论如何,处理这个表结构的最简单方法是首先组合表:

SELECT SUM(Day1Reg) AS sumDay1Reg,
       SUM(Day10T)  AS sumDay10T,
       ...
FROM (SELECT * FROM WeekA
      UNION ALL
      SELECT * FROM WeekB)
WHERE userName = 'JustMe'  -- optional

答案 1 :(得分:0)

SELECT
  (SUM(a.Day1Reg + b.Day1Reg)) AS sumDay1Reg,
  (SUM(a.Day1OT + b.Day1OT)) AS sumDay1OT,
  (SUM(a.Day2Reg + b.Day2Reg)) AS sumDay2Reg,
  (SUM(a.Day2OT + b.Day2OT)) AS sumDay2OT,
  (SUM(a.Day3Reg + b.Day3Reg)) AS sumDay3Reg,
  (SUM(a.Day3OT + b.Day3OT)) AS sumDay3OT
FROM WeekA a,
     WeekB b
WHERE a.userName = 'JustMe' AND b.userName = 'JustMe' --Comment this out for first query