从具有不同值的单个表中多次选择一列

时间:2016-02-24 11:40:31

标签: mysql sql

嗨,我有一个问题,因为我被困在我的一个SQL查询上。 我写了这个SQL查询:

SELECT DISTINCT Date(createddate) as Date,
       (SELECT maxage FROM wob_stock_age 
        WHERE (maxage = a.maxage) AND (totetype='B') 
        GROUP BY Date)AS Blue,

       (SELECT maxage FROM wob_stock_age 
        WHERE (maxage = a.maxage) AND (totetype='V') 
        GROUP BY Date)AS Yellow,

       (SELECT maxage FROM wob_stock_age 
        WHERE (maxage = a.maxage) AND (totetype='N') 
        GROUP BY Date)AS Pink
FROM wob_stock_age as a

正如您所看到的,我在不同的别名下多次选择同一列。然而,结果并不是我所期望的,因为我得到了Null值。

enter image description here

更新:实际上我想为每个日期获得一行,并希望获得所有" totetype" PINK,BLUE和YELLOW在一行中为一个日期。而不是一个日期的3行。

结果将是

    |Date       |Blue|Yellow|Pink|
    ------------------------------
    |2016-02-16 |153 |27    |40  |
    ------------------------------
    |2016-02-17 |152 |26    |40  |

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合执行此操作。你的问题不清楚,但我对你要做的最好的猜测是:

SELECT maxage,
       SUM(CASE WHEN totetype = 'B' THEN 1 ELSE 0 END) as Blue,
       SUM(CASE WHEN totetype = 'V' THEN 1 ELSE 0 END) as Yellow,
       SUM(CASE WHEN totetype = 'N' THEN 1 ELSE 0 END) as Pink
FROM wob_stock_age as a
GROUP BY maxage
ORDER BY maxage ;

答案 1 :(得分:2)

使用OUTER APPLY

SELECT DISTINCT Date(createddate) as [Date],
  BlueTable.Blue,
  YellowTable.Yellow,
  PinkTable.Pink 
 FROM wob_stock_age as a
 OUTER APPLY (
   SELECT maxage as Blue
   FROM wob_stock_age 
   WHERE (maxage = a.maxage) AND (totetype='B') 
   --GROUP BY Date
 )BlueTable
 OUTER APPLY
 (
  SELECT maxage as Yellow
  FROM wob_stock_age 
  WHERE (maxage = a.maxage) AND (totetype='V') 
  --GROUP BY Date
 )YellowTable
 OUTER APPLY(
 SELECT maxage AS Pink
  FROM wob_stock_age 
  WHERE (maxage = a.maxage) AND (totetype='N') 
 --GROUP BY Date
 )PinkTable