我有两个表,我想在加入后找到不同的行数。我的表是:
我想选择用户的名字和(I)用户拥有的书籍数量(通过忽略状态)和(II)用户拥有状态1的书籍数量。所有这些都将从中选择例如,以他/她的名义拥有“Doe”的用户。可能吗?我怎样才能得到这些结果?
http://sqlfiddle.com/#!2/102ce8/3
(姓名,总数,具体数)
John Doe,3,1
Jane Doe,2,1,
答案 0 :(得分:0)
SELECT tu.name,
Count(ts.id),
Sum(CASE
WHEN status = 1 THEN 1
ELSE 0
END)
FROM tblUsers tu
INNER JOIN tblStatus ts
ON ts.id = tu.id
WHERE tu.name LIKE '%doe%'
GROUP BY tu.id
答案 1 :(得分:0)
SELECT nom,count(b.id_user),SUM(b.status)FROM user u,booking b WHERE u.id = b.id_user GROUP BY u.id
GROUP BY是你的朋友;)
答案 2 :(得分:0)
此语句适用于您的SQL Fiddle:
SELECT
name,count(*),SUM(b.status)
FROM users u
INNER JOIN books b
ON u.id=b.user_id
GROUP BY u.id
如果您只想看到Doe Family,请添加如下WHERE子句:
SELECT
name,count(*),SUM(b.status)
FROM users u
INNER JOIN books b
ON u.id=b.user_id
WHERE u.name LIKE '%Doe%'
GROUP BY u.id
如果要为状态列使用不同的值(例如42而不是1),则应使用条件聚合计数,如下所示:
SELECT
name,count(*),SUM(CASE
WHEN b.status = 1 THEN 1
ELSE 0
END)
FROM users u
INNER JOIN books b
ON u.id=b.user_id
WHERE u.name LIKE '%Doe%'
GROUP BY u.id