db2 sql select语句和聚合函数

时间:2014-08-23 08:22:48

标签: sql select db2 subquery

大家好,我有这三张桌子。

> PS: Size(PK), Price
> P: PID(PK),PName 
> S: size(PK,FK1),PID(PK,FK2),quantity

我想选择PName,并且已售出该PName的每种尺寸的数量。 基本上我期待这个结果:

> --------------------------------------------------------
> PName | SSize_Qty | RSize_Qty| LSize_qty |
> ----------------------------------------------------------
> XYZ   | 34            | 15             | 234           |
> ----------------------------------------------------------
> ABC   | 24            | 23             | 87            |
> ----------------------------------------------------------

我尝试了以下代码来获取前两列:

select PName,
(select count(quantity) from Product p, sales s
where P_size = 'P'
and p.pid = s.pid) as Q_P_Size
from sales s, Product p, pricesize ps
where s.PID = p.PID
and ps.P_size = s.P_size
group by PName

但是它给了我所有产品的总量,这不是我想要的 我希望有人可以帮助我这个

1 个答案:

答案 0 :(得分:0)

我建议你先计算每个名字和大小的数量:

select p.pname, ps.size, count(s.quantity) as qty
from Product p
join Sales s
    on s.PID = p.PID
join pricesize ps
    on ps.size = s.size
group by p.pname, ps.size

这会给你类似的东西:

---------------------------------
> PName | Size | Qty| LSize_qty |
> -------------------------------
> XYZ   | P    | 34             |
---------------------------------
> XYZ   | R    | 23             | 
> -------------------------------
> XYZ   | L    | 87             |
---------------------------------
> ABC   | P    | 24             |
---------------------------------
[...] 

现在您可以使用大小写和聚合函数来转置它:

select pname
     , max( case when size = 'P' then qty end ) as SSize_Qty
     , max( case when size = 'R' then qty end ) as RSize_Qty
     , max( case when size = 'L' then qty end ) as LSize_Qty
from (
    select p.pname, ps.size, count(s.quantity) as qty
    from Product p
    join Sales s
        on s.PID = p.PID
    join pricesize ps
        on ps.size = s.size
    group by p.pname, ps.size
)
group by pname;

但由于这是“演示”,我建议你在应用程序中这样做。所有未经测试的,因此可能存在一些输入错误。