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

Posted 旧夏潜入梦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL将一列转换成一行,并将这一行形成新的列相关的知识,希望对你有一定的参考价值。

SQL部分-----

  1. .查询出来要转换的数据
SELECT name FROM dbo.base_pay_type WHERE is_enabled = 1
数据如图:

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 
如图:

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
如图:

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
如图:

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

以上是关于SQL将一列转换成一行,并将这一行形成新的列的主要内容,如果未能解决你的问题,请参考以下文章

SQL 如何把一列的值转换成一行显示

SQL Server将一列的多行内容拼接成一行

excel中怎么将一列中的第一行和最后一行互换,第二行和倒数第二行互换,依次类推

sql 语句怎么将一行拆分成两行

关于SQL Server将一列的多行内容拼接成一行的问题讨论

关于SQL Server将一列的多行内容拼接成一行的问题讨论