我有下表...请参阅下面的
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;
有些想法......
答案 0 :(得分:0)
有两种简单的方法可以获得corrcet版本:
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 |
----------------------
OR
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 |
----------------------
要获得输出,您必须自动创建新列。这不是在数据库中进行分析的好方法,而且非常罕见。每当“迈克”或其他人花费新的东西时,必须更新来自其他观点的选择陈述......
编辑: 第一个视图为您提供每个用户的总结支出。 第二个视图为您提供每个单独的支出,并在其旁边显示用户名。
答案 1 :(得分: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