【问题标题】:SQL query to select multiple products in same invoiceSQL查询在同一张发票中选择多个产品
【发布时间】: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     

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

【问题讨论】:

    标签: sql sql-server


    【解决方案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 ''
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多