我正在编写一个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
我正在使用此查询进行报告。
答案 0 :(得分: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
与partition by
的{{1}}和order by
子句完全匹配。