sql - 按 LEFT(code, 4) 分组并选择其中一个描述为 1
问题描述
我有一个查询为我提供了这个当前输出:
数据
0001 Californian Whole Almonds (Own Label) 0.50
0001 Californian Whole Almonds 1.00
0001 Californian Whole Almonds (Own Label) 1.00
0001 Californian Whole Almonds (Own Label) 3.00
0001 Californian Whole Almonds 6.00
0001 Californian Whole Almonds (Own Label) 6.00
0001 Californian Whole Almonds 10.00
0001 Californian Whole Almonds (Own Label) 10.00
0001 Californian Whole Almonds (HP) 1.92
0001 Californian Whole Almonds (HP - Own Label) 1.92
0001 Californian Whole Almonds (HP - Own Label) 1.50
0002 Flaked Almonds (Own Label) 0.50
0002 Flaked Almonds 1.00
0002 Flaked Almonds (Own Label) 1.00
0002 Flaked Almonds (Own Label) 3.00
0002 Flaked Almonds 6.00
询问
SELECT LEFT(code, 4), description, w.WeightInKilograms AS WeightKG FROM Product p
JOIN TechnicalDatabase.dbo.Weights w on p.searchRef1 = w.Weight
问题
我怎样才能group
一起LEFT(p.code, 4)
,选择一个相同的描述,LEFT(p.code, 4)
最后总结重量?
我试过的
电流输出
0001 Californian Whole Almonds 17.00
0001 Californian Whole Almonds (HP - Own Label) 3.42
0001 Californian Whole Almonds (HP) 2.88
0001 Californian Whole Almonds (Own Label) 20.50
查询已尝试
SELECT LEFT(code, 4), description, SUM(w.WeightInKilograms) AS WeightKG FROM Product p
JOIN TechnicalDatabase.dbo.Weights w on p.searchRef1 = w.Weight GROUP BY LEFT(code, 4), description;
它应该是什么:
由此
0001 Californian Whole Almonds (Own Label) 0.50
0001 Californian Whole Almonds 1.00
0001 Californian Whole Almonds (Own Label) 1.00
0001 Californian Whole Almonds (Own Label) 3.00
0001 Californian Whole Almonds 6.00
0001 Californian Whole Almonds (Own Label) 6.00
0001 Californian Whole Almonds 10.00
0001 Californian Whole Almonds (Own Label) 10.00
0001 Californian Whole Almonds (HP) 1.92
0001 Californian Whole Almonds (HP - Own Label) 1.92
0001 Californian Whole Almonds (HP - Own Label) 1.50
0002 Flaked Almonds (Own Label) 0.50
0002 Flaked Almonds 1.00
0002 Flaked Almonds (Own Label) 1.00
0002 Flaked Almonds (Own Label) 3.00
0002 Flaked Almonds 6.00
对此
0001 Californian Whole Almonds (Own Label) 42.84
0002 Flaked Almonds (Own Label) 11.5
解释
我具体分组,LEFT(p.code, 4)
我需要选择任何描述为 1 并显示权重的总和。只是不知道该怎么做。
解决方案
选择与 LEFT(p.code, 4) 相同的描述之一,最后总结权重?
您想要其中一个描述,然后只需MAX/MIN
在 Description 列上使用并将其从GROUP BY
以下内容中删除:
SELECT LEFT(code, 4),
max(description) as description,
SUM(w.WeightInKilograms) AS WeightKG
FROM Product p
JOIN TechnicalDatabase.dbo.Weights w on p.searchRef1 = w.Weight
GROUP BY LEFT(code, 4);
推荐阅读
- printf - 如何使用 printf 显示没有尾随零的浮点数
- ios - CollectionView 中的同一部分是否可以有 2 个标题?
- geoip - CentOS 6.X、iptables 1.47 和 Geolite2:我怎样才能使它工作?
- python - 映射 DataFrame 索引并前向填充 nan 值
- c# - UserManager.FindByEmailAsync 返回 null,但用户存在于数据库中
- sql-server - 使用服务代理运行时 sp_ogetproperty 失败
- java - 如何根据结果内部对象对mongo聚合查询进行排序
- algorithm - 找到以下代码的上限和下限
- node.js - 仅显示登录用户存在对象数组的记录
- python - 如何将 Userb 第一条消息发送给我?下面的代码有助于获取最新消息。我想要该用户的第一条消息给我