联合行到SQL Server中的列

时间:2017-01-25 18:31:56

标签: sql-server

这是表" tbltask",

task    Ship_Operator   Pick_Operator   Pack_Operator
1       john            kevin           steve
2       kevin           kevin           john
3       steve           john            john
4       steve           steve           steve
5       john            steve           john

现在我需要为每个人获得总金额:发货,拣货,打包

name    ship Total  pick Total  pack Total
john    2           1           3
kevin   1           2           0
steve   2           2           2

我可以使用三个语句来获得结果:

select [Ship_Operator] ,count(*) as task_total  from tbltask 
where [Ship_Operator] in ('john','kevin','steve')
group by [Ship_Operator]

select [Pick_Operator] ,count(*) as task_total from tbltask 
where [Pick_Operator] in ('john','kevin','steve')
group by [Pick_Operator]

select [Pack_Operator] ,count(*) as task_total from tbltask 
where [Pack_Operator] in ('john','kevin','steve')
group by [Pack_Operator]

是否可以使用一个SQL语句? 我们将非常感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

unpivotpivot返回:

with t(task,Ship_Operator,Pick_Operator,Pack_Operator) as (
select '1','john','kevin','steve'  union all
select '2','kevin','kevin','john'  union all
select '3','steve','john','john'   union all
select '4','steve','steve','steve' union all
select '5','john','steve','john')
-------Test data set up ends here------------

select 
    name, Ship_Operator ship_total, Pick_Operator pick_total, Pack_Operator pack_total
from t unpivot (
    name for operation in (Ship_Operator, Pick_operator, Pack_Operator)
) as x pivot (
    count(task) for operation in ([Ship_Operator],[Pick_Operator],[Pack_Operator])
) as x;

产地:

enter image description here

另一种方法是仅使用UNPIVOT然后有条件地聚合:

with t(task,Ship_Operator,Pick_Operator,Pack_Operator) as (
select '1','john','kevin','steve'  union all
select '2','kevin','kevin','john'  union all
select '3','steve','john','john'   union all
select '4','steve','steve','steve' union all
select '5','john','steve','john')
-------Test data set up ends here------------

select 
    name,
    count(case when operation = 'Ship_Operator' then 1 end) ship,
    count(case when operation = 'Pick_Operator' then 1 end) pick,
    count(case when operation = 'Pack_Operator' then 1 end) pack
from t unpivot (
    name for operation in (Ship_Operator, Pick_operator, Pack_Operator)
) as x
group by name;

产地:

enter image description here

答案 1 :(得分:2)

使用UNION组合所有名称并添加新列以识别不同的值。

<强>查询

SELECT t.[Name],
SUM(CASE t.[Col1] WHEN 'Ship' THEN 1 ELSE 0 END) AS [Ship Total],
SUM(CASE t.[Col1] WHEN 'Pick' THEN 1 ELSE 0 END) AS [Pick Total],
SUM(CASE t.[Col1] WHEN 'Pack' THEN 1 ELSE 0 END) AS [Pack Total]
FROM(
    SELECT 'Ship' AS [col1], [Ship_operator] as [Name]
    FROM [tbltask]
    UNION ALL
    SELECT 'Pick', [Pick_operator]
    FROM [tbltask]
    UNION ALL
    SELECT 'Pack' AS [col1], [Pack_operator]
    FROM [tbltask]
)t
GROUP BY t.[Name];

如果你想要特别针对这三个名字的结果。然后在子查询中添加WHERE条件。