列到行SQL

Posted

tags:

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

我正在尝试将包含列的单行转换为多行。

这是我的选择

     select 
'MOE' as TYPE,
SUM(sdl.xx_MOE) as [TOTAL MOE] ,
sdl.xx_PU_MOE,
'MOD' as TYPE,
SUM(sdl.xx_MOD) as [TOTAL MOD],
sdL.xx_PU_MOD,
'MOU' as TYPE,
SUM(sdl.xx_MOU) as [TOTAL MOU],
sdl.xx_PU_MOU
from SaleDocumentLine sdl inner join 
Deal d on sdl.DealId = d.Id 
where d.id = 'CC1800679' and sdl.LineType = 2
group by xx_PU_MOU, xx_PU_MOE, xx_PU_MOD

结果:Result

我希望实现这样的目标:

---------------------------------
|TYPE       | TOTAL | UNIT PRICE|
---------------------------------
|MOE        | 136   |  34       |
---------------------------------
|MOD        | 22    |  34       |
---------------------------------
|MOU        | 122   |  34       |
---------------------------------

我认为我可以使用枢轴,但由于我从未使用它,所以对我来说这有点模糊。

谢谢。

答案

这是一个没有任何样本数据的猜测工作,但是,这应该足以让你开始;只要我猜对了。

我看不到(至少从我们的内容)你有一个包含类型名称的表,因此我使用了包含所需值的CTE:

WITH [Types] AS (
    SELECT [Type]
    FROM (VALUES('MOE'),('MOD'),('MOU')) V([Type]))
SELECT T.[Type],
       SUM(CASE T.[Type] WHEN 'MOE' THEN sdl.xx_MOE
                         WHEN 'MOD' THEN sdl.xx_MOD
                         WHEN 'MOU' THEN sdl.xx_MOU END) AS Total
FROM SaleDocumentLine sdl
     INNER JOIN Deal d ON sdl.DealId = d.Id 
     CROSS JOIN [Types] T
WHERE d.id = 'CC1800679'
  AND sdl.LineType = 2
GROUP BY T.[Type];
另一答案
WITH CTE AS
(
  SELECT *
  from SaleDocumentLine sdl inner join 
  Deal d on sdl.DealId = d.Id 
  where d.id = 'CC1800679' and sdl.LineType = 2
)
SELECT 'MOE' as TYPE,
       SUM(sdl.xx_MOE) as TOTAL,
       xx_PU_MOE 'UNIT PRICE'
FROM CTE
GROUP BY xx_PU_MOE
 UNION ALL 
SELECT 'MOD' as TYPE,
       SUM(sdl.xx_MOD) as TOTAL,
       xx_PU_MOD 'UNIT PRICE'
FROM CTE
GROUP BY xx_PU_MOD
 UNION ALL 
SELECT 'MOU' as TYPE,
       SUM(sdl.xx_MOU) as TOTAL,
       xx_PU_MOU 'UNIT PRICE'
FROM CTE
GROUP BY xx_PU_MOU;
另一答案

试试下面的脚本

;WITH CTE([Type1],TotalMoe,xx_PU_MOE,[Type2],TotalMoD,xx_PU_MOD,[Type3],TotalMoU,xx_PU_MOU)
AS
(
SELECT 'MOE',13.600000000,34.00000000,'MOD',22.00000000,34.00000000,'MOU',122.00000000,34.00000000
)
SELECT   [Type]
        ,TOTAL
        ,UNIT_PRICE 
FROM CTE
CROSS APPLY (VALUES([Type1],TotalMoe,xx_PU_MOE),
                    ([Type2],TotalMoD,xx_PU_MOD),
                    ([Type3],TotalMou,xx_PU_MOU))D ([Type],TOTAL, UNIT_PRICE)

结果

Type    TOTAL           UNIT_PRICE
-------------------------------------
MOE     13.600000000    34.00000000
MOD     22.000000000    34.00000000
MOU     122.000000000   34.00000000

以上是关于列到行SQL的主要内容,如果未能解决你的问题,请参考以下文章

在oracle SQL中将行移动到列和列到行

列到行SQL

DB2 SQL 列到行

多列,多表列到行 unpivot

具有不同日期的列到行

python pandas,某些列到行[重复]