如何基于单列不同值实现列组重复的SQL查询
按月份关联item值的行转列查询实现
我现有table1,结构如下:
| identifier | month | item 1 | item 2 |
|---|---|---|---|
| xyz-1 | 10 | 0 | 0 |
| xyz-2 | 10 | 0 | 0 |
| xyz-1 | 11 | 1 | 1 |
| xyz-2 | 11 | 1 | 1 |
期望得到的查询结果如下:
| identifier | item 1 - 10 | item 2 - 10 | item 1 - 11 | item 2 - 11 |
|---|---|---|---|---|
| xyz-1 | 0 | 0 | 1 | 1 |
| xyz-2 | 0 | 0 | 1 | 1 |
最终目标是生成一年中每个月份对应的item列集合(上述示例仅展示10月、11月数据)。原本认为使用Group By和Join即可实现,但花费一整天仍未找到正确方案。
更新1 - 接近解决方案
参考其他贡献者的建议,我重写了生成初始表的原始查询,此前运行的查询语句为:
TRANSFORM First([Points]) AS ItemPoints SELECT identifier, month FROM [source] GROUP identifier, month PIVOT name;
事后看来该查询显然会生成month列,不符合最终格式要求。我调整后的查询语句如下:
TRANSFORM First([source].Points) AS ItemPoints SELECT [source].identifier FROM [itemNames], [source] GROUP BY [source].identifier ORDER BY ScoreMonth & [itemNames].ItemId PIVOT ScoreMonth & [itemNames].ItemId;
其中[itemNames]是返回唯一item名称(即“item 1”、“item 2”)的查询,最终得到的结果表如下,已经可以基础使用:
| identifier | 10item 1 | 10item 2 | 11item 1 | 11item 2 |
|---|---|---|---|---|
| xyz-1 | 0 | 0 | 1 | 1 |
| xyz-2 | 0 | 0 | 1 | 1 |
更新2 - 问题未完全解决
刚发布上述方案后就发现Transform行的聚合函数导致返回值不正确,我正在重新排查问题,同时尝试DlookUp()函数方案。
更新3 - 最终解决方案
最终发现Transform查询的问题在于ORDER BY和PIVOT行需要引用[source]表而非[itemNames]表,同时我把First()函数替换为Min(),两种聚合函数都可正常运行,最终查询语句如下:
TRANSFORM Min([source].Points) AS ItemPoints SELECT [source].identifier FROM [source] GROUP BY [source].identifier ORDER BY ScoreMonth & '_' & [source].ItemId PIVOT ScoreMonth & '_' & [source].ItemId;
内容的提问来源于stack exchange,提问作者JMather
相关产品推荐
相关产品推荐

