在子查询中动态设置列名

时间:2015-01-12 11:48:38

标签: mysql sql subquery calculated-columns

我有2张桌子。一个名为购买

  

(id,month,purchase,storeid)

和另一个名为 purchases_targets

  

(id,storeid,target1,target2,target3,target4,target5,target6,target7,target8,target9,target10,target11,target12)

purchases_targets中的列名对应于月份,即第1个月的目标= target1。 正常化这对我来说不是一个选择! 我试图做的事情如下:

SELECT DISTINCT

    purchases.month,
    purchases.purchase, 
    CONCAT('target',purchases.month) AS column_name,
    (SELECT 
      column_name 
    FROM purchases_targets
    WHERE storeid = 1) AS 'target'

FROM purchases 
WHERE purchases.storeid = 1

请注意使用上面的 column_name 。我试过这个,结果总是返回目标列的目标+月份。我想知道是否有一种方法可以让我在mysql中工作。如果需要更多信息,请与我们联系。谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用CASE表达式根据month选择不同的列:

SELECT DISTINCT
    p.month,
    p.purchase,
    CASE p.month
        WHEN 1 THEN pt.target1
        WHEN 2 THEN pt.target2
        ...
        WHEN 12 THEN pt.target12
    END AS target
FROM purchases AS p
JOIN purchases_targets AS pt ON p.storeid = pt.storeid
WHERE p.storeid = 1