其实我也没有啥好办法,我甚至推荐你使用楼上说的方法,直接select * 将数据全部查出后,在service中用java处理数据更加方便。
如果要强行使用sql查出来,我这里写了这么一段:
首先因为是同一张表,根据不同条件将结果拼接在一起,我能想到的就是用left join,我按照不同条件将数据分成如下几段:
a段:姓名段,作为left join的主表,只有姓名;
b段:吃了早餐段;
c段:没吃早餐段;
d段:吃了晚餐段;
e段:没吃晚餐段;
f段:吃了饭段;
g段:没吃饭段。
除了a段以外,其他段都是根据自身条件
SELECT
name,
count(*) count,
sum(weight) sum,
然后依次左连接将所有段通过姓名连接到一起,最终组成的sql语句如下:
SELECT
a.name 姓名,
ifnull(b.count, 0) 吃了早餐的次数,
ifnull(b.sum, 0) 吃了早餐的重量,
ifnull(c.count, 0) 没吃早餐的次数,
ifnull(c.sum, 0) 没吃早餐的重量,
ifnull(d.count, 0) 吃了晚餐的次数,
ifnull(d.sum, 0) 吃了晚餐的重量,
ifnull(e.count, 0) 没吃晚餐的次数,
ifnull(e.sum, 0) 没吃晚餐的重量,
ifnull(f.count, 0) 吃了饭的次数,
ifnull(f.sum, 0) 吃了饭的重量,
ifnull(g.count, 0) 没吃饭的次数,
ifnull(g.sum, 0) 没吃饭的重量
FROM
(SELECT DISTINCT name
FROM T) a LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE type = 0 AND status = 0
GROUP BY name) b ON a.name = b.name
LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE type = 0 AND status = 1
GROUP BY name) c ON a.name = c.name
LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE type = 1 AND status = 0
GROUP BY name) d ON a.name = d.name
LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE type = 1 AND status = 1
GROUP BY name) e ON a.name = e.name
LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE status = 0
GROUP BY name) f ON a.name = f.name
LEFT JOIN
(SELECT
name,
count(*) count,
sum(weight) sum
FROM T
WHERE status = 1
GROUP BY name) g ON a.name = g.name
T表结构为:
(因为以name字段进行连接,type和status作为条件,建议以该三个字段作为索引)
T表测试数据为:
运行结果为:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)