Postgresql:如何获得所需的输出,如下所述

时间:2016-02-16 09:49:17

标签: sql postgresql

我有一个名为Box的表:

Box包含以下项目:

1. pen

2. pencil

3. scale

4. eraser

5. sharpener

实际的表结构如下所示:

No        Item       quantity       bought_date
_______________________________________________

 1.        pen              3        14-12-2016

 2.     pencil             10        15-12-2016

 3.        pen              5        16-12-2016

 4.     eraser              7        16-12-2016

 5.  sharpener              6        17-12-2016

 6.     pencil              3        18-12-2016

 7.        pen              3        18-12-2016
需要

输出:

Item         Total_quantity
___________________________

Pencil                   13

Pen                      11

Eraser                    7

Sharpener                 6  

Scale                     0
___________________________

total                    37

请帮我解决这个问题...

3 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT t.item,sum(cast(coalese(b.quantity,'0') as integer)) as total_quantity FROM (
    SELECT 'pen' as item
    UNION
    SELECT 'pencil' as item
    UNION
    SELECT 'scale' as item
    UNION
    SELECT 'eraser' as item
    UNION
    SELECT 'sharpener' as item) t
LEFT OUTER JOIN box b
ON(t.item = b.item)
GROUP BY t.item
UNION
(SELECT 'total',sum(quantity)
FROM box)

我已根据您的评论调整了代码,我认为这就是您想要的。

答案 1 :(得分:0)

select it, sum(s) s from
(
select b.item it, sum(b.qty::integer) s from box b group by b.item
union
select 'total' as item ,sum(qty::integer )total from box group by item  
) as un group by un.it;

答案 2 :(得分:0)

更短更方便的方法是:

with items(item_no, item_name) as (
  values
    (1, 'pen'),
    (2, 'pencil'),
    (3, 'scale'),
    (4, 'eraser'),
    (5, 'sharpener')
  )
select
  items.item_name,
  coalesce(sum(box.quantity::int), 0) as total_quantity
from
  items
    left join box on (box.item = items.item_name)
group by
  items.item_name

union all

select
  'total',
  coalesce(sum(box.quantity::int), 0)
from
  box