根据其他列SQL

时间:2017-02-20 07:51:41

标签: sql group-by sum

 PID  |  ChildPID | value
------|-----------|-------
 3835 |   3934    |  1
 3835 |   3935    |  0
 3835 |   3936    |  0
 3835 |   3939    |  1
 3836 |   3940    |  0
 3836 |   3941    |  0
 3836 |   3942    |  0

我需要像

这样的结果
PIDCountinvalue|  Childcountinvalue | PIDCountoutvalue|  Childcountoutvalue 
---------------|--------------------|-----------------|-------------------|
 1             |   2                |  1              |      5

表示我需要根据相应值的总和得到PID,ChildPID的计数,如果子Id属于一个具有完整值 0 的PID,则只有PID将在 PIDCountoutvalue中计数列,或者如果在总结该PID的所有ChildPID之后它有> 0 ,我将被视为 PIDCountinvalue ,并进入Childcount根据相应的值输入/输出它。

解释:

 PIDCountinvalue|  Childcountinvalue | PIDCountoutvalue|  Childcountoutvalue 
 ---------------|--------------------|-----------------|-------------------|
  1(3835)       |   2 (3934,3939)    | 1 (3836) |5(3935,3936,3940,3941,3942)

总共有两个PID:(3835,3836)和PID:3835有4个子女(3934,3935,3936,3939)(孩子的值> 0的总和)和PID:3836有4个子女(3940, 3941,3942)(childs的值的总和= 0),所以如果你在各个PId的下面加上childIds的值,如果值count的总和= 0那么相应的PID将被计为 PIDCountoutvalue 否则它会在 PIDCountinvalue 之下,就像3836处于outvalue计数而3835处于值计数中一样。

1 个答案:

答案 0 :(得分:0)

您的解释不是很清楚,我无法理解您的逻辑,但这里有一个可以帮助您的示例代码。您可以轻松修改它以满足您的需求。

CREATE TABLE Table1
    ([PID] varchar(6), [ChildPID] varchar(11), [value] int)
;

INSERT INTO Table1
    ([PID], [ChildPID], [value])
VALUES
    ('3835', '3934', '1'),
    ('3835', '3935', '0'),
    ('3835', '3936', '0'),
    ('3835', '3939', '1'),
    ('3836', '3940', '0'),
    ('3836', '3941', '0'),
    ('3836', '3942', '0')
;

--You can use a common table expression to "build" a table and then to query what you need.
with 
cte as
(
    select PID, ChildPID, sum(value) [Sum]
    from Table1 
    group by PID, ChildPID
)

--Now just build you columns with the aggregated data you need.
select 
     (select 
        count(distinct PID) 
        from cte 
        where [Sum] > 0)        as PIDCountinvalue    --Get count of PIDs with sum of values more than 0
    ,(select 
        count(ChildPID) 
        from cte 
        where [Sum] > 0)        as Childcountinvalue  --Get count of ChildPIDs that have values larger than 0
    ,(select sum(I.PIDs) from
        (select
            count(PID) PIDs
            from cte 
            group by PID
            having sum([Sum]) <= 0) I)  as PIDCountoutvalue   --Get count of PIDs with sum of value less than 0
    ,(select 
        count(ChildPID) 
        from cte 
        where [Sum] <= 0)       as Childcountoutvalue --Get count of ChildPIDs that have values less than 0

该查询的输出正是您想要的。但是,由于我的逻辑不清楚,这可能不是您完整数据的最终解决方案。但我希望它至少有一点帮助。