【问题标题】:SQL - Counting number of instances of each result on another tableSQL - 计算另一个表上每个结果的实例数
【发布时间】:2020-10-08 14:53:12
【问题描述】:

我有一个 postgresql 数据库和一个简单的查询,它从几个不同的表中提取数据以报告特定项目及其销售情况。 我需要计算每件商品的订单总数,但我还没有成功。

查询会提取每个可供出售的特定商品。我需要查询“order_item”表并计算条目数或每个单独的项目......这将是订单表上每个项目的“kitchen_item_name”的具体计数。

select distinct
kitchen_item.id as "id",
kitchen_item.name as "Dish Name",
kitchen_item.price as "Price",
kitchen_item.created as "Created On",
account.firstname||',
'||account.lastname as "Seller Name",
account.email as "Seller Email",
account.phone as "Seller Phone", 
address.address as "Seller Address", 
address.zip as "Seller Zip", 
address.neighborhood as "Seller Neighborhood"
from kitchen_item
left join menu_item on (kitchen_item.id = menu_item.kitchen_item_id)
left join order_item on (menu_item.id = order_item.menu_item_id)
left join store on (kitchen_item.store_id = store.id)
left join account on (store.account_id = account.id)
left join store_address on (store.id = store_address.store_id)
left join address on (store_address.address_id = address.id)

这个计数需要是输出中的最后一列,我有两个想法——第一个是子查询:

(select count distinct order_item.kitchen_item_name from order_item)

在“from”行之前添加这一行是行不通的。

所以我想知道是否需要创建一个临时表并将原始查询插入其中,然后加入计数?这一般是怎么做的?

【问题讨论】:

  • 始终加入密钥 - menu_item 已经存在。
  • @clamp 对,我在 menu_item 键上加入了 order_item 表...我的印象是这样做会使计算 order_item 表上的订单数量变得更加困难,并且它适用于每一行

标签: postgresql count


【解决方案1】:

该死,我想我真的想通了!

select distinct
kitchen_item.id as "id",
kitchen_item.name as "Dish Name",
kitchen_item.price as "Price",
kitchen_item.created as "Created On",
account.firstname||',
'||account.lastname as "Seller Name",
account.email as "Seller Email",
account.phone as "Seller Phone", 
address.address as "Seller Address", 
address.zip as "Seller Zip", 
address.neighborhood as "Seller Neighborhood",
(
SELECT
    COUNT(DISTINCT menu_item_id)
    FROM order_item
    WHERE order_item.menu_item_id = menu_item.id
    AND order_item.kitchen_item_name = kitchen_item.name
) AS "Total Dish Sold"
from kitchen_item
left join menu_item on (kitchen_item.id = menu_item.kitchen_item_id)
left join order_item on (menu_item.id = order_item.menu_item_id)
left join store on (kitchen_item.store_id = store.id)
left join account on (store.account_id = account.id)
left join store_address on (store.id = store_address.store_id)
left join address on (store_address.address_id = address.id)

重要的一点是-

(
SELECT
    COUNT(DISTINCT menu_item_id)
    FROM order_item
    WHERE order_item.menu_item_id = menu_item.id
    AND order_item.kitchen_item_name = kitchen_item.name
) AS "Total Dish Sold"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2010-09-15
    • 2018-09-12
    • 2017-08-01
    • 2016-03-06
    相关资源
    最近更新 更多