MySQL SELECT - 使用列切换行

时间:2014-03-21 15:01:49

标签: mysql select union pivot-table

我为标题缺乏解释而道歉,因为我不知道该怎么称呼我要做什么,如果你知道我在寻找什么,请修改。

这是我目前的表格:

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

1 个答案:

答案 0 :(得分:0)

如果您没有尝试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

这有点像一种hacky方式,但它会根据您的请求转换您的数据。看到sql小提琴的结果... http://sqlfiddle.com/#!2/55f59/45