我的表price_matrix
是
id service_id deadline edu_level paper_stand price
------------------------------------------------------
1 5 20 GCES A 50
2 5 10 GCSE A 30
3 5 20 GCSE B 10
2 5 10 GCSE B 40
如何编写一个能让我得到以下格式的结果的查询
deadline service_id paper_stand A paper_stand B edu_level
-----------------------------------------------------------------
20 5 50 10 GCES
10 5 30 40 GCSE
我正在使用的查询是
SELECT `paper_stand` , `deadline` , `price`
FROM `price_matrix`
WHERE `edu_level` = 'GCSE/ A Levels' && `service_id` =5
ORDER BY `paper_stand` , `deadline`
我正在使用MYSQL
任何人都可以帮我解释如何以理想的格式获得结果吗?
由于
答案 0 :(得分:1)
你可以JOIN
表格自己。
SELECT a.deadline,
a.service_id,
a.price AS paper_stand_a,
b.price AS paper_stand_b,
a.edu_level
FROM price_matrix AS a JOIN price_matrix AS b
ON a.deadline = b.deadline AND a.paper_stand = 'A' AND b.paper_stand = 'B'
GROUP BY a.deadline;
您也可以在没有加入的情况下执行此操作。我只使用MAX
获取价格的非NULL值。可能有更好的方法来完成这一部分。
SELECT deadline,
service_id,
MAX(IF(paper_stand = 'A', price, NULL) AS paper_stand_a,
MAX(IF(paper_stand = 'B', price, NULL) AS paper_stand_b,
edu_level
FROM price_matrix
GROUP BY deadline;
答案 1 :(得分:0)
我们可以在select上使用Inner Query来获取结果。
我没有SQL查询构建器,但编写的查询会给你一个想法。
SELECT deadline, service_id, edu_level,
(SELECT price FROM price_matrix tmp
WHERE pm.deadline = tmp.deadline
AND pm.service_id = tmp.service_id
AND tmp.paper_stand = 'A') AS PaperStandA,
(SELECT price FROM price_matrix tmp
WHERE pm.deadline = tmp.deadline
AND pm.service_id = tmp.service_id
AND tmp.paper_stand = 'B') AS PaperStandB,
FROM price_matrix pm
GROUP BY deadline, service_id, edu_level
答案 2 :(得分:0)
试
SELECT A.deadline, A.edu_level, A.service_id, A.price as paper_standA, B.price as paper_standB
FROM (
SELECT *
FROM price_matrix
WHERE paper_stand = 'A'
) AS a, (
SELECT *
FROM price_matrix
WHERE paper_stand = 'B'
) AS b
WHERE a.service_id = b.service_id
AND b.deadline = a.deadline