通过比较列的字符串值来汇总某些行的结果

时间:2014-01-16 20:14:32

标签: sql select

我有这张桌子:

fy       period       division         employee_id      category_name      amount
2013     4            Sales            123452           Salary             130000
2013     4            Marketing        124232           Salary             120000
2013     4            Sales-WC         124244           Bonus              10000
2013     4            Sales            124244           Adjustments        1000
2013     4            Sales-WC         897287           Salary             65000

我正在尝试获取一个查询,该查询将为我提供每个类别的金额总和,但诀窍是我想在它上面加上'-WC'时将它组合起来。

此查询:

select division_name, category_name, SUM(amount) as amount
FROM tblStaff 
where fy=2013 and period=4
group by division_name, category_name

让我接近我想要的东西:

division      category_name        amount
Sales         Salary               130000
Sales-WC      Salary               65000
Sales-WC      Bonus                1000
Marketing     Salary               120000
Sales         Adjustments          1000

但我想要的是:

division      category_name        amount
Sales         Salary               195000
Sales-WC      Bonus                1000
Marketing     Salary               120000
Sales         Adjustments          1000

其中category_name'Salary'已合并为'Sales'和'Sales-WC'。

我尝试使用如下的案例陈述开始:

SELECT case 
   when division_name = division_name + '-WC' THEN division_name
   ELSE 'not found' --did this just for testing
   END as 'division_name',
   category_name,
   SUM(amount)
   FROM tblStaff
   where fy=2013 and period=4
   group by division_name, category_name

但似乎我不能在case语句的部分中使用列名,因为当我运行此命令时,我只是为每一行得到division_name ='not found'。

有什么想法吗?谢谢!

4 个答案:

答案 0 :(得分:3)

我想你想要LIKE

SELECT
  case 
    when division_name LIKE '%-WC' THEN replace(division_name, '-WC', '') 
    ELSE division_name
  END as 'division_name',
...

或者你可以这样做:

SELECT
  replace(division_name, '-WC', '') as division_name,
  ...
GROUP BY replace(division_name, '-WC', '')

答案 1 :(得分:2)

您必须检查division_name是否以'-WC'结尾,然后将其剥离:

select
   case 
      when division_name like '%-WC' 
      then substring(division_name from 1 for position('-WC' in division_name) -1) 
      else division_name
   end,
   category_name, SUM(amount) as amount
FROM tblStaff 
where fy=2013 and period_=4
group by 
   case 
      when division_name like '%-WC' 
      then substring(division_name from 1 for position('-WC' in division_name) -1) 
      else division_name
   end,
   category_name   

答案 2 :(得分:1)

您可以创建一个视图,从视图中删除“-WC”,然后在该视图上使用您的第一个查询。

CREATE VIEW _table AS
SELECT CASE WHEN LEFT(division, 3) = '-WC' THEN RIGHT(division, LENGTH(division)-3) ELSE division END AS _division, .... FROM table

答案 3 :(得分:0)

SELECT case division_name
WHEN division_name = division_name + '-WC' THEN division_name
ELSE 'not found'

http://technet.microsoft.com/en-us/library/ms189074(v=sql.105).aspx