将数据组合到单个单元中,同时对单独的单元进行求和

时间:2017-08-03 18:48:20

标签: sql sql-server

我不知道如何很好地说出我的问题,所以我将从返回的数据开始:

prop_id | assess_value | sale_id

35004 | 401200 | 1920831

35005 | 40500 | 1920831

35023 | 11300 | 1920831

34380 | 139100 | 1915846

127959 | 286400 | 1915882

我希望它返回:

prop_id | assess_value | sale_id

35004,35005,35023 | 453000(3个包裹的总和)| 1920831

34380 | 139100 | 1915846

127959 | 286400 | 1915882

所以我的主要目标是将sale_id字段中的所有宗地组合成一个字符串,但仅当销售ID具有多个prop_id时,然后总结所有这些的评估值。这是我用来获取第一组数据的查询...

select 
pv1.[prop_id],
pv1.[assessed_val],
ld1.[sale_id]
from dbo.land_detail as ld1     
join dbo.property_val as pv1 on 
pv1.[prop_id] = ld1.[prop_id] and
pv1.[prop_val_yr] = ld1.[prop_val_yr] and
pv1.[sup_num] = ld1.[sup_num]
left join dbo.sale as sale1 on  
sale1.[chg_of_owner_id] = ld1.[sale_id]
where   
pv1.[prop_inactive_dt] is null
order by sale_id, prop_id

prop_id的数据类型为INT
assess_val是数据类型numeric(14,0)
sale_id的数据类型为INT

2 个答案:

答案 0 :(得分:0)

将所有内容放入临时表(#temp),如下所示。然后进行自联接以选择值。有几种使用(SUFF(),XML PATH等)进行连接的方法。在互联网上搜索如何将行连接成逗号分隔的字符串,请参阅this链接,例如

select 
pv1.[prop_id],
pv1.[assessed_val],
ld1.[sale_id],
sale1.[sl_price],
sale1.[sl_dt],
(pv1.[assessed_val]/sale1.[sl_price]) as Ratio
--------Temp Table------------
INTO #temp
------------------------------
from dbo.land_detail as ld1 with(nolock)    
join dbo.property_val as pv1 with(nolock) on    
pv1.[prop_id] = ld1.[prop_id] and
pv1.[prop_val_yr] = ld1.[prop_val_yr] and
pv1.[sup_num] = ld1.[sup_num]
left join dbo.sale as sale1 with(nolock) on 
sale1.[chg_of_owner_id] = ld1.[sale_id]
where   
sale1.sl_dt <= '04/30/16' and
sale1.sl_dt >= '05/01/15' and
pv1.[sub_type] = 'r' and
pv1.[prop_val_yr] = 2016 and
pv1.[prop_inactive_dt] is null
order by sale_id, prop_id

答案 1 :(得分:0)

您可以使用WITH创建临时表,然后可以使用STUFF()FOR XML PATH将prop_id字段连接成一行

WITH temp AS (
select pv1.[prop_id],
       pv1.[assessed_val],
       ld1.[sale_id],
       sale1.[sl_price],
       sale1.[sl_dt],
       (pv1.[assessed_val]/NULLIF(sale1.[sl_price],0) as Ratio
  from dbo.land_detail as ld1 with(nolock)
  join dbo.property_val as pv1 with(nolock)
    on pv1.[prop_id] = ld1.[prop_id]
   and pv1.[prop_val_yr] = ld1.[prop_val_yr]
   and pv1.[sup_num] = ld1.[sup_num]
  left join dbo.sale as sale1 with(nolock)
    on sale1.[chg_of_owner_id] = ld1.[sale_id]
 where sale1.sl_dt <= '04/30/16'
   and sale1.sl_dt >= '05/01/15'
   and pv1.[sub_type] = 'r'
   and pv1.[prop_val_yr] = 2016
   and pv1.[prop_inactive_dt] is null
 order by sale_id, prop_id
)

SELECT STUFF(( SELECT ', ' + CAST(prop_id AS VARCHAR)
                FROM temp
                WHERE sale_id = t.sale_id
                FOR XML PATH(''),TYPE)
                .value('.','NVARCHAR(MAX)'),1,2,'') AS parcels,
       SUM(t.assessed_val) assessed_val,
       t.sale_id,
       t.sl_price,
       t.sl_dt,
       SUM(t.ratio) ratio
  FROM temp t
 GROUP BY t.sale_id,
          t.sl_price,
          t.sl_dt
 ORDER BY t.sale_id DESC