SQL将一列转换成一行,并将这一行形成新的列

时间:2020-12-09 10:51:23

SQL部分-----

  1. .查询出来要转换的数据
SELECT name FROM dbo.base_pay_type WHERE is_enabled = 1
数据如图:
SQL将一列转换成一行,并将这一行形成新的列

2.将查询到的数据转换成行,以逗号隔开,以【】包裹

SELECT STUFF((SELECT  '[' + name + '],'  
FROM(SELECT name FROM dbo.base_pay_type WHERE is_enabled = 1) a  FOR  XML PATH('')  ), 1,0, '') AS Name 
如图:
SQL将一列转换成一行,并将这一行形成新的列
 

3,去掉最后一个逗号

SELECT LEFT(a.Name,LEN(a.Name)-1) AS Name FROM (SELECT STUFF((SELECT  '[' + name + '],'  
FROM(SELECT name FROM dbo.base_pay_type WHERE is_enabled = 1) a  FOR  XML PATH('')  ), 1,0, '') AS Name ) AS a
如图:
SQL将一列转换成一行,并将这一行形成新的列
 

4,这一行形成新的列,用PIVOT实现

SELECT * FROM (
 select sellerid,pay_type_name,cast(sum(amount) as decimal(18,2)) as payamout from (
 SELECT distinct oi.order_guid,ss.SellerId,bs.name AS pay_type_name,op.amount
 FROM dbo.shop_sellers AS ss
 LEFT JOIN dbo.order_item oi ON ss.SellerId=oi.tracking_id
 LEFT JOIN dbo.order_list ol ON ol.order_guid = oi.order_guid
 LEFT JOIN dbo.order_pay op ON ol.order_guid=op.order_guid
 LEFT JOIN dbo.base_pay_type bs ON op.pay_type_id=bs.pay_type_id
 INNER JOIN dbo.shops s ON s.ShopGuid=ol.owner
 WHERE bs.is_enabled=1 AND op.is_received=1 AND order_status='finished' and pay_status='paid' 
 and s.ShopId IN(SELECT ShopId FROM dbo.shops WHERE 1=1 and shopid=15 or ParentShopId=15) 
 AND ol.order_time between '2018-01-17' and '2018-08-17 23:59:59') a
 GROUP BY SellerId,pay_type_name) AS PA PIVOT(MAX( payamout ) FOR 
 pay_type_name IN ([现金],[支付宝],[微信支付],[会员卡],[康品汇会员卡],[银联扫码支付]))PPA
如图:SQL将一列转换成一行,并将这一行形成新的列

C#后台代码,先将一列转换成一行,以逗号隔开,【】包裹

string SQL = "SELECT LEFT(a.Name,LEN(a.Name)-1) AS Name FROM (SELECT STUFF((SELECT  '[' + name + '],'  
FROM(SELECT name FROM dbo.base_pay_type WHERE is_enabled = 1) a FOR XML PATH('') ), 1, 0, '') AS Name ) AS a
"; DataTable dt = dbAccess.ExecuteTable(SQL); string filwes = dt.Rows[0]["name"].ToString();
得到的结果如上面标题3,然后拼接SQL,将filwes作为参数输入下面SQL语句

SELECT * FROM (
select sellerid,pay_type_name,cast(sum(amount) as decimal(18,2)) as payamout from (
SELECT distinct oi.order_guid,ss.SellerId,bs.name AS pay_type_name,op.amount
FROM dbo.shop_sellers AS ss
LEFT JOIN dbo.order_item oi ON ss.SellerId=oi.tracking_id
LEFT JOIN dbo.order_list ol ON ol.order_guid = oi.order_guid
LEFT JOIN dbo.order_pay op ON ol.order_guid=op.order_guid
LEFT JOIN dbo.base_pay_type bs ON op.pay_type_id=bs.pay_type_id
INNER JOIN dbo.shops s ON s.ShopGuid=ol.owner
WHERE bs.is_enabled=1 AND op.is_received=1 AND order_status='finished' and pay_status='paid'
and s.ShopId IN(SELECT ShopId FROM dbo.shops WHERE 1=1 {1}) {2}) a
GROUP BY SellerId,pay_type_name) AS PA PIVOT(MAX( payamout ) FOR pay_type_name IN (‘“+filwes+”’))PPA