SqlServer查询使用Group by和Order by

时间:2015-01-26 12:30:39

标签: sql-server

        SELECT * FROM (SELECT 1 rn,
        SUM(BILL_DETAIL.x_bill_quantity)      as BILL_QUANTITY,
        MIN(BILL_DETAIL.x_billable_to)        as BILLABLE_TO,
        MIN(BILL_DETAIL.x_billable_yn)        as BILLABLE_YN,
        AVG(BILL_DETAIL.x_bill_rate)          as BILL_RATE,
        MIN(BILL_DETAIL.x_cost_rate)          as COST_RATE,
        MIN(BILL_DETAIL.x_cost_total)          as COST_TYPE,
        LISTAGG(BILL_DETAIL.objid, ',') WITHIN GROUP(ORDER BY BILL_DETAIL.objid) as ID_LIST
     FROM  table_x_gsa_bill_detail BILL_DETAIL
      WHERE (1=1)
       GROUP BY (DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO  || ',' || DETAIL_CLASS || ',' || COST_TYPE || ',' || BILL_RATE) 
      ORDER BY DECODE(BILLABLE_YN, 1, 'Billable', 'Non-Billable') || ',' || BILLABLE_TO  || ',' || DETAIL_CLASS || 
  ) dt
WHERE rn BETWEEN 0 AND 1

如何在上述查询中使用Case关键字代替Decode?我无法将上述查询转换为分组依据和按顺序排序。

实际上我需要按照BILLABLE_YN,BILLABLE_TO,DETAIL_CLASS, COST_TYPE, BILL_RATE字段中的汇总值进行分组。

在Oracle中,我可以使用decode关键字运行上述查询,但在SQL Server中,我无法在group by中使用上述查询的BILLABLE_YN字段别名。

我尝试使用以下方法,但它是错误的,因为在这里我没有使用按功能分组的字段的聚合值。如何将查询转换为SQL Server语法?

GROUP BY (case BILLABLE_YN
          when 1 then 'Billable'
          when 0 then 'Non-Billable'
          else 'Non-Billable' End BILLABLE_YN  + ',' + BILLABLE_TO  + ',' + DETAIL_CLASS + ',' + COST_TYPE + ',' + BILL_RATE)

1 个答案:

答案 0 :(得分:0)

GROUP BY CASE MIN(BILL_DETAIL.x_billable_yn) 
WHEN 1 THEN 'Billable' ELSE 'Non-Billable' END + ',' +
MIN(BILL_DETAIL.x_billable_to) + ',' + DETAIL_CLASS + ',' + 
MIN(BILL_DETAIL.x_cost_total) + ',' + AVG(BILL_DETAIL.x_bill_rate) 

我不知道LISTAGG功能是什么。如果您需要拆分字符串列,他们会在该站点上搜索它。有很多这样的话题。