Postgresql (Rails 3) 合并列上的行(同一表)
首先,我一直使用mysql,现在升级到postgresql。 sql 语法更加严格并且某些行为不同,因此我的问题。
我一直在寻找如何合并表上的 postgresql 查询中的行,例如
id | name | amount
0 | foo | 12
1 | bar | 10
2 | bar | 13
3 | foo | 20
和 get
name | amount
foo | 32
bar | 23
我发现的最接近的是 将重复记录合并为具有相同表和表字段的 1 条记录
sql 返回“name”的重复项:
scope :tallied, lambda { group(:name, :amount).select("charges.name AS name,
SUM(charges.amount) AS amount,
COUNT(*) AS tally").order("name, amount desc") }
我需要的是
scope :tallied, lambda { group(:name, :amount).select("DISTINCT ON(charges.name) charges.name AS name,
SUM(charges.amount) AS amount,
COUNT(*) AS tally").order("name, amount desc") }
,除了返回给定名称的第一行之外,应该返回具有给定名称的所有行的混搭(添加的数量)
在mysql中,附加 .group(:name)
(不是需要初始组)来选择将按预期工作。
这似乎是一项日常任务,应该很容易。执行此操作的简单方法是什么?请指出我正确的道路。
PS我想在这里学习(其他人也是如此),不要只是把sql扔到我脸上,请解释一下。
First, I've been using mysql for forever and am now upgrading to postgresql. The sql syntax is much stricter and some behavior different, thus my question.
I've been searching around for how to merge rows in a postgresql query on a table such as
id | name | amount
0 | foo | 12
1 | bar | 10
2 | bar | 13
3 | foo | 20
and get
name | amount
foo | 32
bar | 23
The closest I've found is Merge duplicate records into 1 records with the same table and table fields
sql returning duplicates of 'name':
scope :tallied, lambda { group(:name, :amount).select("charges.name AS name,
SUM(charges.amount) AS amount,
COUNT(*) AS tally").order("name, amount desc") }
What I need is
scope :tallied, lambda { group(:name, :amount).select("DISTINCT ON(charges.name) charges.name AS name,
SUM(charges.amount) AS amount,
COUNT(*) AS tally").order("name, amount desc") }
except, rather than returning the first row of a given name, should return mash of all rows with a given name (amount added)
In mysql, appending .group(:name)
(not needing the initial group) to the select would work as expected.
This seems like an everyday sort of task which should be easy. What would be a simple way of doing this? Please point me on the right path.
P.S. I'm trying to learn here (so are others), don't just throw sql in my face, please explain it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道 RoR 在后台做什么,但我猜测
group(:name, :amount)
将运行按名称、金额分组的查询。您要查找的是group by name
:如果您将
amount
附加到group by
子句,查询将执行此操作 - - 即count(*)
将返回每个名称中每个金额出现的次数,而sum()
将返回该数字乘以该金额。I've no idea what RoR is doing in the background, but I'm guessing that
group(:name, :amount)
will run a query that groups by name, amount. The one you're looking for isgroup by name
:If you append
amount
to thegroup by
clause, the query will do just that -- i.e.count(*)
would return the number of times each amount appears per name, and thesum()
would return that number times that amount.