长期读者,第一次海报。
我正在努力巩固一张桌子,以便在运输途中丢失所售商品的价格。在此表中,我们有四种产品,三个原产国,三个过境国(货物在传递给客户之前首先运往哪里)和三个目的地国家。表格如下。
Status Product Count Origin Transit Destination
--------------------------------------------------------------------
Delivered Shoes 100 Germany France USA
Delivered Books 50 Germany France USA
Delivered Jackets 75 Germany France USA
Delivered DVDS 30 Germany France USA
Not Delivered Shoes 7 Germany France USA
Not Delivered Books 3 Germany France USA
Not Delivered Jackets 5 Germany France USA
Not Delivered DVDS 1 Germany France USA
Delivered Shoes 300 Poland Netherlands Canada
Delivered Books 80 Poland Netherlands Canada
Delivered Jackets 25 Poland Netherlands Canada
Delivered DVDS 90 Poland Netherlands Canada
Not Delivered Shoes 17 Poland Netherlands Canada
Not Delivered Books 13 Poland Netherlands Canada
Not Delivered Jackets 1 Poland Netherlands Canada
Delivered Shoes 250 Spain Ireland UK
Delivered Books 20 Spain Ireland UK
Delivered Jackets 150 Spain Ireland UK
Delivered DVDS 60 Spain Ireland UK
Not Delivered Shoes 19 Spain Ireland UK
Not Delivered Books 8 Spain Ireland UK
Not Delivered Jackets 8 Spain Ireland UK
Not Delivered DVDS 10 Spain Ireland UK
我想创建一个新表,显示交付的商品数量,而不是一行交付,如下所示。
Product Delivered Not_Delivered Origin Transit Destination
Shoes 100 7 Germany France USA
Books 50 3 Germany France USA
Jackets 75 5 Germany France USA
DVDS 30 1 Germany France USA
Shoes 300 17 Poland Netherlands Canada
Books 80 13 Poland Netherlands Canada
Jackets 25 1 Poland Netherlands Canada
DVDS 90 0 Poland Netherlands Canada
Shoes 250 19 Spain Ireland UK
Books 20 8 Spain Ireland UK
Jackets 150 8 Spain Ireland UK
DVDS 60 10 Spain Ireland UK
我已经看了一些其他帖子,到目前为止我还没找到我正在寻找的内容。也许这里的问题是代码中会有多个WHERE语句,以确保我不会将所有鞋子组合在一起,而是将所有国家/地区组合在一起。
这可以用SQL吗?
答案 0 :(得分:1)
这样的东西?
select
product
,sum(case when status = 'Delivered' then count else 0 end) as delivered
,sum(case when status = 'Not Delivered' then count else 0 end) as not_delivered
,origin
,transit
,destination
from table
group by
product
,origin
,transit
,destination
答案 1 :(得分:0)
这很容易;而不是每个产品,原产地,公交,目的地和状态一行,您只需要每个产品,原产地,公交和目的地一个结果行。因此按这四列分组并有条件地汇总:
select
product, origin, transit, destination,
sum(case when status = 'Delivered' then "count" else 0 end) as delivered,
sum(case when status = 'Not Delivered' then "count" else 0 end) as not_delivered
from mytable
group by product, origin, transit, destination;
BTW:对列名使用关键字不是一个好主意。我使用双引号来使用您的列count
,这是标准SQL,但我不知道它是否适用于Google BigQuery。也许它必须是"Count"
而不是"count"
或其他完全不同的东西。)
答案 2 :(得分:0)
node_b