【问题标题】:Selecting one column multiple times from a single table with different values从具有不同值的单个表中多次选择一列
【发布时间】:2016-02-24 11:40:30
【问题描述】:

您好,我有一个问题,因为我被困在我拥有的一个 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 值时,结果不是我所期望的。

更新:实际上,我想为每个日期获取一行,并希望在一个日期的一行中获取所有“totetype”粉色、蓝色和黄色。而不是一个日期的 3 行。

所以结果是

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

【问题讨论】:

  • 您的问题不清楚。您的查询生成一列,但您想要的结果有三列。
  • 您使用的是哪个 DBMS?
  • MySQL 这就是为什么外部应用不起作用

标签: mysql sql


【解决方案1】:

您可以使用条件聚合来做到这一点。您的问题尚不清楚,但我对您要做什么的最佳猜测是:

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

【讨论】:

  • 不幸的是我使用的是mysql并且不支持外部应用
猜你喜欢
  • 1970-01-01
  • 2010-10-11
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2017-12-24
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
相关资源
最近更新 更多