这个问题的 SQL 查询是什么?

发布于 2024-11-09 06:31:18 字数 457 浏览 0 评论 0原文

我有一个数据库表交易,其中存储用户进行的与购买、销售和下订单相关的所有交易。

表格 http://img691.imageshack.us/img691/1948/stackoverflow.jpg

我想编写一个 SQL 查询,其结果如下:
1. 每个人进行的所有交易的计数。
2. 每种订单类型的交易计数
3.结果应从最大总计数到最低计数排序
4. 结果应该只获取前 10 个人的信息(使用“limit 0,10”)。

我想获取已经组织好的数据,而不是获取原始数据并在 PHP 中进行操作

所以我想为这个问题编写一个优化的查询,因为这个表包含数千行 请指导我

谢谢...

I have a database table transaction which stores all the transaction made by users related to purchase, sell and placing order.

Table http://img691.imageshack.us/img691/1948/stackoverflow.jpg

I want to write one SQL query which gives result as following :
1. count of all transactions each person has made.
2. transactions count for every order type
3. result should be sorted from biggest total count to the lowest
4. And the result should fetch only first 10 persons info(using 'limit 0,10').

I want to fetch data which is organized already rather than fetching raw data and manipulating in PHP

So i want to write an optimized query for this problemm because this table contains thousands of rows
Please guide me

thanks...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘你却要生生世世 2024-11-16 06:31:18

尝试这样的事情:

SELECT p_id, COUNT(1) AS Total, SUM(CASE WHEN order_type = 'purchased' THEN 1 ELSE 0 END) AS PurchaseCount, SUM(CASE WHEN order_type = 'placed order' THEN 1 ELSE 0 END) AS PlacedOrderCount, SUM(CASE WHEN order_type = 'sold' THEN 1 ELSE 0 END) AS SoldCount
FROM transaction
GROUP BY p_id
ORDER BY Total DESC
LIMIT 0, 10

为了回应您的后续评论,我相信这会得到您想要的结果
(其中计数限制设置为根据您的需要截止)

SELECT p_id, item_name, COUNT(item_name) as ItemCount
FROM transaction
GROUP BY p_id, item_name
HAVING COUNT(item_name) > 100

Try something like:

SELECT p_id, COUNT(1) AS Total, SUM(CASE WHEN order_type = 'purchased' THEN 1 ELSE 0 END) AS PurchaseCount, SUM(CASE WHEN order_type = 'placed order' THEN 1 ELSE 0 END) AS PlacedOrderCount, SUM(CASE WHEN order_type = 'sold' THEN 1 ELSE 0 END) AS SoldCount
FROM transaction
GROUP BY p_id
ORDER BY Total DESC
LIMIT 0, 10

In response to your follow up comment, I believe this would get what your after
(Where the count restriction is set to a cut off for your needs)

SELECT p_id, item_name, COUNT(item_name) as ItemCount
FROM transaction
GROUP BY p_id, item_name
HAVING COUNT(item_name) > 100
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文