1

我的桌子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

谁能帮我解释一下如何获得所需格式的结果?

谢谢

4

3 回答 3

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;
于 2012-11-16T06:17:06.100 回答
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
于 2012-11-16T06:16:28.000 回答
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
于 2012-11-16T06:32:52.530 回答