繁体   English   中英

有没有办法在 T-SQL 中使用 pivot 或其他东西来实现以下目标?

[英]Is there a way to achieve below using pivot or something else in T-SQL?

我正在尝试在 T-SQL 中使用 pivot 实现以下目标:

品牌 收入 b品牌 收入` 品牌 c 收入
分支 1 20,000 分公司 6 9000 分公司 9 11000
分支 3 15000 分支 5 2000 分公司 6 8000
分公司 9 10000 分行 10 1500 分支 4 5000

但是我得到了这个结果:

品牌 b品牌 品牌 c 分支
20000 null null 分支 1
15000 null null 分支 3
10000 null 11000 分公司 9
null 9000 8000 分公司 6
null 2000 null 分支 5
null 1500 null 分行 10

我用过这个查询

select
    brand a, 
    brand b,
    brand c,
    Branch
from
    (select
         r.Branch,
         r.Revenue,
         r.brand
     from 
         (--data from sales table
          select 
              branch, sum(revenue) Revenue, p.brand, 
              Row_number() over (partition by (p.brand) order by sum(revenue) desc) [rank] 
          from sales s
          join Product p on s.prodid = p.prodid
          join branch b on s.Branch = b.branch
          where p.brand in ('brand a', ' brand b', ' brand c')
            and time between @startdate and @enddate
          group by branch, p.brand) r
     where 
         r.rank <= 3) p1
pivot
    (max(revenue)
         for brand in (`brand a`, `brand b`, `brand c`)
    ) piv

只需使用条件聚合:

select max(case when brand = 'brand a' then branch end) as branch_a,
       sum(case when brand = 'brand a' then revenue end) as revenue_a,
       max(case when brand = 'brand b' then branch end) as branch_b,
       sum(case when brand = 'brand b' then revenue end) as revenue_b,
       max(case when brand = 'brand c' then branch end) as branch_c,
       sum(case when brand = 'brand c' then revenue end) as revenue_c
from (select b.branch, sum(revenue) as Revenue, p.brand, 
             row_number() over (partition by p.brand order by 
      sum(revenue) desc) as seqnum
      from sales s join
           Product p
           on s.prodid = p.prodid join
           branch b
           on s.Branch = b.branch
      where p.brand in ('brand a',' brand b',' brand c') and
            time between @startdate and @enddate
      group by branch, p.brand
     ) pb
group by seqnum;

暂无
暂无

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

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