如何在SQL中进行逐列和逐行操作

时间:2017-01-30 16:19:07

标签: sql transformation data-manipulation

我对SQL查询中的行方式和列方式操作有疑问。我将使用以下示例数据表演示我的问题:

Person           Income      Hours worked   Day
A                100         10             1
A                200         9              2
B                300         8              1 
B                400         7              2
C                500         6              1
C                600         5              2

我想写一个查询,我可以得到(A + B)和C的总收入,工作时数和每小时收入。这是:

Person           Income      Hours worked   Income / Hour
A + B            1000        34             1000 / 34
C                1100        11             1100 / 11

我将如何在SQL中执行此操作?

非常感谢提前!

4 个答案:

答案 0 :(得分:2)

对于MySQL,我们可以这样做:

SELECT CASE WHEN t.Person IN ('A','B') THEN 'A + B' ELSE t.Person END AS Person
     , SUM(t.Income)                                                  AS Income
     , SUM(t.`Hours Worked`)                                          AS `Hours Worked`
     , CONCAT( SUM(t.Income) , ' / ' , SUM(t.`Hours Worked`) )        AS `Income / Hour`
 FROM mytable t
GROUP BY CASE WHEN t.Person IN ('A','B') THEN 'A + B' ELSE t.Person END

这种模式在大多数其他关系数据库中都可以使用,但是对于转义不稳定的列名称有不同的处理方式。

对于Oracle,用双引号括起标识符而不是反引号。 (即用双引号替换反引号,并附上包含小写字母或其他特殊字符的列名。)

对于SQL Server,将标识符括在方括号中{... {1}}。

答案 1 :(得分:2)

只是为了给出另一种方法,这是一个UNION方法:

Error in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]) : 
  there is no package called ‘scales’
Errore: package or namespace load failed for ‘forecast’

编辑:蒂姆更快。

答案 2 :(得分:1)

您可以使用case表达式将人AB的行视为相同并汇总。

select 
case when person in ('A','B') then 'A+B' else person end as person
,sum(income) as income
,sum(hoursworked) as hoursworked
,sum(income)/sum(hoursworked) as income_hour
from yourtable
group by case when person in ('A','B') then 'A+B' else person end

答案 3 :(得分:1)

您可以在子查询中使用UNION ALL

SELECT Person, Income, [Hours worked], [Income / Hour]    
FROM (
  SELECT 'A + B' AS Person,
          SUM(Income) AS Income,
          SUM([Hours worked]) AS [Hours worked],
          SUM([Day]) AS [Hours worked]
  FROM dbo.TableName
  WHERE Person IN('A', 'B')           

  UNION ALL

  SELECT 'C' AS Person,
          SUM(Income) AS Income,
          SUM([Hours worked]) AS [Hours worked],
          SUM([Day]) AS [Hours worked]
  FROM dbo.TableName
  WHERE Person = 'C'
) x

如果要排序,可以在外部查询中应用ORDER BY