繁体   English   中英

没有聚合列的SQL PIVOT

[英]SQL PIVOT without aggregate columns

create table Product_Price
    (
      id int,
      dt date,
      SellerName varchar(20),
      Product varchar(10),
      ShippingTime varchar(20),
      Price money
    )

    insert into Product_Price values (1, '2012-01-16','Sears','AA','2 days',32)
    insert into Product_Price values (2, '2012-01-16','Amazon', 'AA','4 days', 40)
    insert into Product_Price values (3, '2012-01-16','eBay','AA','1 days', 27)
    insert into Product_Price values (4, '2012-01-16','Walmart','AA','Same day', 28)
    insert into Product_Price values (5, '2012-01-16','Target', 'AA','3-4 days', 29)
    insert into Product_Price values (6, '2012-01-16','Flipcart','AA',NULL, 30)


select *
from
(select dt, product, SellerName, sum(price) as price 
from product_price group by  dt, product, SellerName) t1

pivot (sum(price) for SellerName in ([amazon],[ebay]))as bob
) 

我想要在输出中再增加2列(一个是AmazonShippinTime另一个是eBayshippintime )。 我如何获得这些? 小提琴: http ://sqlfiddle.com/#!3/2210d/1

由于您需要在两列上旋转并在两列上使用不同的聚合,因此我将使用带有CASE表达式的聚合函数来获取结果:

select
  dt, 
  product,
  sum(case when SellerName = 'amazon' then price else 0 end) AmazonPrice,
  max(case when SellerName = 'amazon' then ShippingTime end) AmazonShippingTime,
  sum(case when SellerName = 'ebay' then price else 0 end) ebayPrice,
  max(case when SellerName = 'ebay' then ShippingTime end) ebayShippingTime
from product_price
group by dt, product;

请参阅带有演示的SQL Fiddle 结果如下:

|         DT | PRODUCT | AMAZONPRICE | AMAZONSHIPPINGTIME | EBAYPRICE | EBAYSHIPPINGTIME |
|------------|---------|-------------|--------------------|-----------|------------------|
| 2012-01-16 |      AA |          40 |             4 days |        27 |           1 days |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM