0

我有下表...请参见下文

table users:
-------------
| id | name |
-------------
| 1  | mike |
| 2  | john |
| 3  | bill |
-------------

table trans:
---------------
| uid | spent | 
---------------
| 1   | 5.00  |
| 1   | 6.00  |
| 2   | 5.00  |
| 3   | 5.00  |
| 3   | 10.00 |
---------------

expected output:
----------------------------
| id | name | spent | spent |
----------------------------
| 1  | mike | 5.00  | 6.00  |
| 2  | john | 5.00  | null  |
| 3  | bill | 5.00  | 10.00  |
----------------------------

我正在使用以下查询...

SELECT d.id, d.name, m.spent
   FROM users d 
  INNER JOIN trans m
     ON d.id = m.uid GROUP BY id;

但它并没有向我展示我想要什么,有人帮助......

我已经尝试了以下代码...看起来我在附近但还没有....

SELECT d.id, d.name, m.spent
IF (m.id=5.00, 'spent', '') AS spent,
IF (m.id=6.00, 'spent1', '') AS spent1 
   FROM users d 
  INNER JOIN trans m
     ON d.id = m.uid GROUP BY id;

有点想法...

4

2 回答 2

0

有两种简单的方法可以获得正确的版本:

SELECT d.id, d.name, sum(m.spent)
FROM users d 
INNER JOIN trans m
ON d.id = m.uid GROUP BY (d.id, d.name)
ORDER BY d.id;

你会得到

----------------------
| id | name | spent  |
----------------------
| 1  | mike | 11.00  |
| 2  | john |  5.00  |
| 3  | bill | 15.00  |
----------------------

或者

SELECT d.id, d.name, m.spent
FROM users d 
INNER JOIN trans m
ON d.id = m.uid
ORDER BY d.id;

你会得到

----------------------
| id | name | spent  |
----------------------
| 1  | mike |  5.00  |
| 1  | mike |  6.00  |
| 2  | john |  5.00  |
| 3  | bill |  5.00  |
| 3  | bill | 10.00  |
----------------------

要获得输出,您必须自动创建新列。这不是在数据库中进行分析的好方法,而且非常罕见。每次“迈克”或其他人花费新东西时,都必须更新来自其他视图的选择语句......

编辑:第一个视图为您提供每个用户的汇总支出。第二个视图为您提供每笔支出,旁边有用户名。

于 2013-08-15T09:22:42.093 回答
0

您在这里的主要困难是您可能有一个或两个相同 ID 的条目。这不仅意味着我们需要“计数”事物,而且我们必须确定“第一”和“第二”行(请记住,表是无序集)。

很难推断出您想要构建结果表的方式(准确地说是如何区分“左”和“右”花费列)。假设这是“min”和“max”:

select uid, spent as s1, NULL as s2 from trans group by uid having count(*) = 1 
union select t1.uid, t1.spent, t2.spent from trans as t1 join trans as t2 
          on t1.uid = t2.uid and t1.spent < t2.spent;

生产:

+------+------+-------+
| uid  | s1   | s2    |
+------+------+-------+
|    2 | 5.00 |  NULL |
|    1 | 5.00 |  6.00 |
|    3 | 5.00 | 10.00 |
+------+------+-------+

关于您最初的问题,我们只处于JOIN预期结果的“一个”:

select users.id, users.name, S.* from users join
(
    select uid, spent as s1, NULL as s2 from trans group by uid having count(*) = 1 
    union select t1.uid, t1.spent, t2.spent from trans as t1 join trans as t2 
              on t1.uid = t2.uid and t1.spent < t2.spent;
) AS S
ON users.id = S.uid
于 2013-08-15T10:16:23.330 回答