SQL - 根据B列中的值添加列A.

时间:2016-06-22 14:51:29

标签: sql sql-server

我尝试根据另一个值中的值添加列中的值。但输出并不是我所期待的。任何帮助tweeking此查询将有所帮助。 例如:

SELECT [custNo]
  ,[cityNo]
  ,sum([TransactionCount]) as transcount
FROM [log].[dbo].[TransactionSummary]
where [format] = 23
or [format] = 25
or [format] = 38
or [format] >=400 and [format] <= 499
or [format] >=800 and [format] <= 899
and transactiondate = '6/21/16'
group by custno, cityno

将产生如下输出:

custno  cityno  transcount
1       10220   4
1       10277   6
501     10284   9
501     10284   17
604     10248   4
604     10248   317

我想要的是输出更像是:

custno  cityno  transcount
1       10220   4
1       10277   6
501     10284   26 (sum of 17+9)
604     10248   321 (sum of 317+4)

2 个答案:

答案 0 :(得分:0)

  1. 将您的不同数据存储在表变量..

    declare @Table Table(ID int identity, custNo int, cityNo int, Other varchar(500))
    
    insert into @Table(custNo, cityNo)
       SELECT distinct 
           [custNo], [cityNo]
       FROM 
           [log].[dbo].[TransactionSummary]
       WHERE
           [format] = 23
           or [format] = 25
           or [format] = 38
           or [format] >= 400 and [format] <= 499
           or [format] >= 800 and [format] <= 899
           and transactiondate = '6/21/16'
    
  2. 使用while循环使用Other函数将您的说明存储在COALESCE列中

    declare @i int, @cnt int, @custNo  int
    declare @Result VARCHAR(Max) 
    
    select @cnt = count(*), @i = 1 
    from @Table
    
    while @i <= @cnt
    begin
        select @custNo = custNo 
        from @Table 
        where ID = @i
    
       (if select count(*)  FROM TransactionSummary where custNo =@custNo )>1
    

    开始    设置@Result =&#39;&#39;    SELECT @Result = COALESCE(@Result +&#39; +&#39;,&#39;&#39;)+ cast(TransactionCount as varchar(50))    FROM TransactionSummary其中custNo = @ custNo    更新@Table设置其他=&#39;(&#39; + @结果+&#39;的总和)&#39;其中id = @id 结束   设置@ i = @ i + 1 端

  3. 最后写下你的查询..

    SELECT [tr.custNo]   [tr.cityNo]  ,cast(sum([tr.TransactionCount])as varchar(50))+ isnull(Other,&#39;&#39;)transcount FROM [log]。[dbo]。[TransactionSummary] tr 左外连接@Table t on tr.custNo = t.custNo和tr.cityNo = t.cityNo 其中[格式] = 23 或[格式] = 25 或[格式] = 38 或[格式]&gt; = 400和[格式]&lt; = 499 或[格式]&gt; = 800和[格式]&lt; = 899 和transactiondate =&#39; 6/21/16&#39; group by custno,cityno

答案 1 :(得分:0)

类似这样的事情

SELECT [custNo]
  ,[cityNo]
  ,SUM(TransactionCount) over (Partition by CustNo) as 'SUM' as transcount
FROM [log].[dbo].[TransactionSummary]
where [format] = 23
or [format] = 25
or [format] = 38
or [format] >=400 and [format] <= 499
or [format] >=800 and [format] <= 899
and transactiondate = '6/21/16'
group by custno, cityno