将行转换为列值 - 返回单行

时间:2014-11-18 12:09:54

标签: sql sql-server axapta dynamics-ax-2012

我对SQL编程很新,而且我正在处理有关我们财务发布的报告。

过帐使用1到多个维度组合的字符串进行排序。这些维度存储在数据库中,我希望能够将字符串分成每个财务行的列。

DimensionAttributeLevelValueAllView包含维度字符串,但它分成行

Displayvalue  
703310
5022
PEN

我尝试使用case-when结构将值过滤为列,但随后生成单独的行:

Account  | Department  | Misc
703310 
         | 5022
                       | PEN

而不是

Account  | Department  | Misc
703310   | 5022        | PEN

下面的查询应该将上面的维度与相应的过帐行组合在一起,但它会创建一个单独的行,如上所示,每行的财务金额相同。

SELECT
    Case When B.ValueOrdinal='1' Then B.Displayvalue end as 'Account',
    case when B.ValueOrdinal='2' then B.Displayvalue end as 'Department',
    case when B.ValueOrdinal='3' then B.Displayvalue end as 'Misc',
    A.Text,
    Sum(A.reportingcurrencyamount) as 'Posted Amount',
    A.Recid

From GeneralJournalAccountEntry A
    Inner Join DimensionAttributeLevelValueAllView B on A.Ledgerdimension = B.ValueCombinationRecID
    Inner Join DIMENSIONATTRIBUTEVALUECOMBINATION C on A.Ledgerdimension = C.RecID

Where C.accountstructure in ('5637145326','5637165585')

Group by A.Recid, B.Valueordinal, B.Displayvalue, A.Text

我考虑过动态Pivot功能,但我似乎无法弄清楚如何将它用于此原因。

提前致谢

1 个答案:

答案 0 :(得分:4)

您正在通过太多字段进行聚合。试试这个:

SELECT MAX(Case When B.ValueOrdinal='1' Then B.Displayvalue end) as Account,
       MAX(case when B.ValueOrdinal='2' then B.Displayvalue end) as Department,
       MAX(case when B.ValueOrdinal='3' then B.Displayvalue end) as Misc,
       A.Text,
       Sum(A.reportingcurrencyamount) as PostedAmount,
       A.Recid
From GeneralJournalAccountEntry A Inner Join
     DimensionAttributeLevelValueAllView B
     on A.Ledgerdimension = B.ValueCombinationRecID Inner Join
     DIMENSIONATTRIBUTEVALUECOMBINATION C
     on A.Ledgerdimension = C.RecID
Where C.accountstructure in ('5637145326','5637165585')
Group by A.Recid,  A.Text;

我不鼓励你对列别名使用单引号。仅对字符串和日期常量使用单引号。通常,只是尝试给出不需要任何转义字符的列名(例如,不要在名称中放置空格)。