聚合 SQL 函数以从每个分组中仅获取一个
我有一个表,需要对 SQL-Server 2000 中的许多字段进行规范化。 它包含 2 个字段,我用它们来提出规范定义的不同组合。 ID 和费率:有多行相同的 ID 和费率
我首先通过对 ID 和费率组合进行分组来创建临时表。
SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total
INTO #Temp
GROUP BY ID
现在我使用 Distinct 来仅查找唯一的组合。因此,我将有多个 ID 组共享相同的 Total 和 IDCounts
SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp
现在我的问题是如何将单个 ID 连接回 IDCounts 和 Total 的不同分组并将其放入新表中?只要我使用同一组中的 ID,组中的哪一个 ID 并不重要。
I have a table that I need to normalize with many fields In SQL-Server 2000.
It contains 2 fields which I'm using to come up with distinct combination as defined by the specs.
ID and Rate: there are multiple rows of same IDs and Rates
I first created a temp table by grouping the IDs and Rates combination.
SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total
INTO #Temp
GROUP BY ID
Now I use Distinct to find only the unique combinations. So i'll have multiple ID groups sharing same Total and IDCounts
SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp
Now my question is how to join a single ID back to that distinct grouping of IDCounts and Total and put that into a new table? It doesn't matter which one of the IDs in the groups as long as I use one from the same grouping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
保留临时表(尽管这可以在单个查询中完成):
Keeping your temp tables (although this could all be done in a single query):
将“Min(ID) AS FirstID”添加到#uniques 中的选择中。
Add "Min(ID) AS FirstID" to the select into #uniques.
尝试这样的事情:
Try something like this: