" SQL案例然后"累积结果

时间:2016-05-28 08:44:48

标签: sql sql-server

我有三列表,第一列是月数,第二列是公司名称,第三列是该公司的投诉数。 有些公司在几个月内没有抱怨,我想生成一个表,其中一个轴是月轴,另一个是公司名称,表中每个单元格的值都是抱怨数。

你能帮我写一下这个SQL查询吗? 这是我尝试使用pivot(有Jason的帮助,但它不会工作,并返回null.P.S. Numb是浮动的,投诉和月份是nvarchar)

select *
from 
(
  select Numb, Complaint, Months
  from Rezayat94
) src
pivot
(
  sum(numb)
  for months in ([1], [2], [3],[4],[5],[6], [7], [8],[9],[10],[11],[12])
) piv;

感谢。 :)

3 个答案:

答案 0 :(得分:1)

试试这个。如果有任何问题请通知。

select Numb, 
      Complaint,
      [1] AS Jan, 
      [2] as Feb, 
      [3] as Mar,
      [4] as Apr,
      [5] as May,
      [6] as Jun,
      [7] as Jul,
      [8] as Aug,
      [9] as Sep,
      [10] as Oct,
      [11] as Nov,
      [12] as Dec
from Rezayat94
pivot
(
  sum(numb)
  for months in ([1], [2], [3],[4],[5],[6], [7], [8],[9],[10],[11],[12])
) piv;

答案 1 :(得分:1)

您不必使用数据透视表。

DECLARE @COMPLAINTS TABLE ([MONTH] VARCHAR(3),COMPANY VARCHAR(1), NUMB FLOAT)
INSERT INTO @COMPLAINTS
VALUES 
('Jan','A',1),
('Feb','A',2),
('Mar','A',3),
('Apr','A',4),
('May','A',5),
('Jun','A',6),
('Jul','A',7),
('Aug','A',8),
('Sep','A',9),
('Oct','A',10),
('Nov','A',11),
('Dec','A',12),
('Jan','B',1),
('Feb','B',2),
('Mar','B',3),
('Apr','B',4),
('May','B',5),
('Jun','B',6),
('Jul','B',7),
('Aug','B',8),
('Sep','B',9),
('Oct','B',10),
('Nov','B',11),
('Dec','B',12),
('Jan','C',1),
--('Feb','C',2),
('Mar','C',3),
--('Apr','C',4),
('May','C',5),
--('Jun','C',6),
('Jul','C',7),
--('Aug','C',8),
('Sep','C',9),
--('Oct','C',10),
('Nov','C',11),
('Dec','C',12)

SELECT  COMPANY Company,
        sum(CASE WHEN [MONTH] = 'Jan' then numb else 0 end) as 'Jan',
        sum(CASE WHEN [MONTH] = 'Feb' then numb else 0 end) as 'Feb',
        sum(CASE WHEN [MONTH] = 'Mar' then numb else 0 end) as 'Mar',
        sum(CASE WHEN [MONTH] = 'Apr' then numb else 0 end) as 'Apr',   
        sum(CASE WHEN [MONTH] = 'May' then numb else 0 end) as 'May',
        sum(CASE WHEN [MONTH] = 'Jun' then numb else 0 end) as 'Jun',
        sum(CASE WHEN [MONTH] = 'Jul' then numb else 0 end) as 'Jul',
        sum(CASE WHEN [MONTH] = 'Aug' then numb else 0 end) as 'Aug',
        sum(CASE WHEN [MONTH] = 'Sep' then numb else 0 end) as 'Sep',
        sum(CASE WHEN [MONTH] = 'Oct' then numb else 0 end) as 'Oct',
        sum(CASE WHEN [MONTH] = 'Nov' then numb else 0 end) as 'Nov',
        sum(CASE WHEN [MONTH] = 'Dec' then numb else 0 end) as 'Dec'
FROM    @COMPLAINTS
GROUP   BY COMPANY

并且在没有投诉的情况下,总和返回0值。执行计划看起来并不比枢轴更昂贵(无论如何在这个小测试样本中)

答案 2 :(得分:0)

for months in ([1], [2], [3],[4],[5],[6], [7], [8],[9],[10],[11],[12])

仅当值<1>,“2”,“3”存储在列中时,此功能才有效。您指定了列的nvarchar数据类型。因此,请将月份列中的值替换为 [1],[2] ...等

例如,你有 Jan 2月 ...等等所以请使用类似的东西

for months in ([Jan], [Feb],... , [Dec])

希望这会有所帮助