TSQL来计算字段并进行总结

时间:2017-06-16 14:42:21

标签: sql sql-server tsql

没有这种合并的经验,但我希望它是例程(希望如此)它计算引发我的列。实际数据是~20k行:

数据格式:

State   Owner   Job1    Job2    Job3    Job4
TN      Joe     123     456             234 
TN      Frank           456     789     
FL      Joe     123     456
FL      Frank   123

需要的结果:

State Owner JobCount
TN  Joe     3
TN  Frank   2
FL  Joe     2
FL  Frank   1

汇总至所有者

Owner   JobCount
Joe     5
Frank   3

4 个答案:

答案 0 :(得分:2)

我认为PIVOT套房最好,因为工作岗位数量可能会增加:

;WITH cte AS 
(SELECT [State]
      ,[Owner]
      ,[Job]
      ,[JobN]
FROM (
        SELECT
             [State]
            ,[Owner]
            ,Job1
            ,Job2
            ,Job3
            ,Job4
        FROM #state
     ) AS p
UNPIVOT
(JobN FOR [Job] IN
(Job1,Job2,Job3,Job4)
) AS unpvt)
--SELECT [State], [Owner], COUNT(1) AS JobCount
--FROM cte
--GROUP BY [State], [Owner]
SELECT [Owner], COUNT(1) AS JobCOunt
FROM cte
GROUP BY [Owner]

评论行是您请求的第一个查询。我主要创建了一个像这样的临时表#state:

CREATE TABLE #state
(
    [State] VARCHAR(2)
    ,[Owner] VARCHAR(20)
    ,[Job1] INT
    ,[Job2] INT
    ,[Job3] INT
    ,[Job4] INT
)

答案 1 :(得分:1)

对于州/所有者

select  State, Owner, count(cs.Jobs) as JobCount
from yourtable 
cross apply (values (Job1),(Job2),(Job3),(Job4)) cs (Jobs)
Group By State, Owner

向所有者推送

select Owner, count(cs.Jobs) as JobCount
from yourtable 
cross apply (values (Job1),(Job2),(Job3),(Job4)) cs (Jobs)
Group by Owner

注意:这会将示例数据中的空白视为表中的NULL

答案 2 :(得分:1)

这是您的TSQL for result 1

SELECT 
    State
    ,Owner 
    ,Sum (
    (
        CASE 
            WHEN Job1 IS NULL THEN 0 
            ELSE 1 
        END)+
        (CASE 
            WHEN  Job2 IS NULL THEN 0 
            ELSE 1 
        END) + 
        (CASE 
            WHEN Job3 IS NULL THEN 0 
            ELSE 1 
        END)+
        (CASE 
            WHEN Job4 IS NULL THEN 0 
            ELSE 1 
        END))
FROM table
GROUP BY State, OWNER

答案 3 :(得分:1)

另一个选择......只是为了好玩, GROUPING SETS

您将一次性获得所有者/州级别和所有者级别

Select [Owner]
      ,[State]
      ,JobCount = sum(isnull(sign(Job1),0)+isnull(sign(Job2),0)+isnull(sign(Job3),0)+isnull(sign(Job4),0))
From  YourTable
Group By Grouping Sets ([State],[Owner]),([Owner])
Order By case when [State] is null then 1 else 0 end

返回

Owner   State   JobCount
Frank   FL      1
Frank   TN      2
Joe     FL      2
Joe     TN      3
Joe     NULL    5
Frank   NULL    3