[英]Selecting one column multiple times from a single table with different values
嗨,我有一个问题,因为我被困在其中一个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 |
您可以使用条件聚合来做到这一点。 您的问题尚不清楚,但是我对您要执行的操作的最佳猜测是:
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 ;
使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.