数据透视表排序日期时间列

时间:2017-07-04 16:51:58

标签: sql pivot-table

我有以下部分的sql语句来转动动态列。列数(ClosingDate)是可变的:

@MessageDriven(mappedName = "jms/testQueue", activationConfig = {
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"
            ),
        @ActivationConfigProperty(propertyName  = "connectionFactoryJndiName",
                              propertyValue = "jms/testQueueFactory"),
    @ActivationConfigProperty(propertyName = "acknowledgeMode",
                                      propertyValue = "Auto-acknowledge")
})
public class JMSMessageConsumer implements MessageListener {

private final static Logger LOGGER = Logger.getLogger(JMSMessageConsumer.class);

    public JMSMessageConsumer() {
    }

    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                long startTime = System.nanoTime();
        processOperation(message);
        } catch (JMSException e) {
                LOGGER.debug("Error in exception" + e);
            }
}

问题在于select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ClosingDate + '_'+ c.col) from #TmpT cross apply ( select 'Cnt' col union all select 'TT' ) c FOR XML PATH('') , TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') 列转换为ClosingDate,并且它们的排序方式为varchar,而不是varchar

有没有办法按date订购?谢谢!

1 个答案:

答案 0 :(得分:0)

您可以先尝试将它们转换为日期:

select @cols = STUFF((SELECT distinct ',' + 
                             QUOTENAME(CONVERT(VARCHAR(8),ClosingDate,112) + '_'+ c.col) 
                      from #TmpT 
                      cross apply 
                      (
                        select 'Cnt' col
                        union all
                        select 'TT'
                      ) c 
            FOR XML PATH('') , TYPE         
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')