有人可以帮助解决这种复杂的情况
我有两张桌子
Table1:
id | status
----------------
1 | New
2 | New
3 | Pending
其中table2是
表2:
id | table1_id
---------------
1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 2
7 | 3
8 | 3
我正在尝试提取状态值,因此尝试使用简单的
SELECT t1.status FROM table1 t1 LEFT OUTER JOIN table2 t2 ON t1.id=t2.table1_id
给出结果
New
New
New
我无法使用不同的,因为我是一些计算,任何想法,以避免在这里重复?
使用case语句我需要一个像
这样的结果 id | New | Pending
---------------------
1 | 1 | 0
2 | 1 | 0
3 | 0 | 1
现在
id | New | Pending
---------------------
1 | 3 | 0
2 | 3 | 0
3 | 0 | 2
答案 0 :(得分:1)
SELECT DISTINCT t1.status
会为您提供不同的价值观。但是,由于您不想使用DISTINCT
,因此您可以添加GROUP BY t1.status
它与DISTINCT
相同:
SELECT t1.status, COALESCE(COUNT(DISTINCT t2.table1_id), 0) AS total
FROM table1 t1
LEFT OUTER JOIN table2 t2 ON t1.id=t2.table1_id
GROUP BY t1.status;
但是这样GROUP BY
对于不同的值只是没用,最好使用DISTINCT
。
答案 1 :(得分:1)
你在找这个吗?
select id, max(t1 = 'New') as New, max(t1 = 'Pending') as Pending
from table1 t1 left outer join
table2 t2
on t1.id = t2.table1_id
group by t1.id;