对于标题缺乏解释,我深表歉意,因为我不知道该怎么称呼我想做的事情,如果您知道我要寻找的内容,请进行修改。

这是我当前的表格:

prodID | seller  |  price
123      seller1    5000
123      seller2    3000
123      seller3    5500
123      seller4    3500
500      seller2    55
500      seller5    60
200      seller1    35
200      seller2    25
200      seller3    35


现在我要在上面的GROUP BY prodID并将每列列出为卖方价格,该价格可能是NULL,即:

prodID  | seller1 | seller2 | seller3 | seller4 | seller5
123       5000      3000      5500      3500      null
500       null      55        null      null      60
200       35        25        35        null      null


我不知道有多少独特的卖家,因此将其视为动态的而不是固定的。

我认为我所研究的内容不需要PIVOT TABLE,但是如果出错,请更正。我也尝试过UNION并合并同一张表,但这似乎效率不高,因为我不知道有多少卖家以及他们的名字是:

效率低下:

SELECT
    MT.prodID, MT.price, CT.price
from
    `table` MT,
    `table` CT
WHERE
    MT.prodID = CT.prodID
        AND MT.seller != CT.seller
GROUP BY MT.prodID

最佳答案

好吧,如果您不想尝试使用PIVOT TABLE并且不能使用另一种编程语言来执行此操作(这将是最佳选择)……您可以做的就是这个。

SELECT
    t.prodID,
    t1.seller1,
    t.seller2,
    t2.seller3,
    t3.seller4,
    t4.seller5
FROM
(
    SELECT
        m1.prodID, m1.price AS seller2
    FROM myTable AS m1
    WHERE m1.seller LIKE "seller2"
) AS t

LEFT JOIN
(
    SELECT
        m.prodID,
        m.price AS seller1
    FROM myTable AS m
    WHERE m.seller LIKE "seller1"
) AS t1 ON t.prodID = t1.prodID

LEFT JOIN
(
    SELECT
        m2.prodID,
        m2.price AS seller3
    FROM myTable AS m2
    WHERE m2.seller LIKE "seller3"
) AS t2 ON t2.prodID = t.prodID

LEFT JOIN
(
    SELECT
        m3.prodID,
        m3.price AS seller4
    FROM myTable AS m3
    WHERE m3.seller LIKE "seller4"
) AS t3 ON t3.prodID = t.prodID

LEFT JOIN
(
    SELECT
        m4.prodID,
        m4.price AS seller5
    FROM myTable AS m4
    WHERE m4.seller LIKE "seller5"
) AS t4 ON t4.prodID = t.prodID


这有点麻烦,但是它会根据您的请求转置数据。请参见sql小提琴以获得结果... http://sqlfiddle.com/#!2/55f59/45

关于mysql - MySQL SELECT-用列切换行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22562317/

10-12 13:32