SQL查询在同一张发票中选择多个产品

Posted

技术标签:

【中文标题】SQL查询在同一张发票中选择多个产品【英文标题】:SQL query to select multiple products in same invoice 【发布时间】:2018-01-18 01:41:58 【问题描述】:

我正在编写一个 sql 查询来显示所有发票。发票有多个产品。我使用 INNER JOIN 从多个表中进行选择。我得到的结果是:

INV No.   Client        Product       Total
---------------------------------------------
inv1   client name1     product1     100.00
inv1   client name1     product2     100.00
inv1   client name1     product3     100.00
inv2   client name2     product1     150.00
inv2   client name2     product3     150.00

是否可以这样显示结果:

INV No.   Client        Product       Total
---------------------------------------------
inv1   client name1     product1     100.00
                        product2     
                        product3     
inv2   client name2     product1     150.00
                        product3     

我将此查询用于报告目的。

【问题讨论】:

【参考方案1】:

这是可能的。这种美学工作通常应该在应用层完成。问题是结果取决于排序——而 SQL 表和结果集通常是无序的。

但是,您可以使用窗口函数来做到这一点:

select (case when row_number() over (partition by inv_no order by product) = 1
             then inv_no
        end) as inv_no,
       (case when row_number() over (partition by inv_no order by product) = 1
             then client
        end) as client,
       product,
       (case when row_number() over (partition by inv_no order by product) = 1
             then total
        end) as total
from t
order by inv_no, product;

请注意,最外面的查询有一个order by,它与row_number()partition byorder by 子句完全匹配。

【讨论】:

太棒了!工作.. 非常感谢.. 它在那个单元格中显示为 NULL,我们可以将其显示为空白(“”)吗? @User27 。 . .您可以将else '' 添加到字符串列。如果有些是数字,那么您需要将数字格式化为字符串(比如使用str()),然后使用else ''

以上是关于SQL查询在同一张发票中选择多个产品的主要内容,如果未能解决你的问题,请参考以下文章

如何在同一个sql查询中更新和选择记录

用于分配付款的 Oracle SQL 查询

SQL 查询:如何在排名列值中使用时间戳列

如何在 WooCommerce 中使用 SQL 查询选择特定类别的产品

更新查询在同一张表上的 Sql 查询死锁

同一张表上的多个连接,在一个查询中计数