联盟在外部查询

时间:2017-03-24 16:15:25

标签: sql sql-server sql-server-2008-r2

我尝试使用UNION组合多个行,但我还需要提取其他数据。我的想法是在外部查询中使用UNION,但我似乎无法使其工作。或者我是不是错了?

我的数据是这样的:

+------+------+-------+---------+---------+
|  ID  | Time | Total | Weekday | Weekend |
+------+------+-------+---------+---------+
| 1001 | AM   |     5 |       5 |       0 |
| 1001 | AM   |     2 |       0 |       2 |
| 1001 | AM   |     4 |       1 |       3 |
| 1001 | AM   |     5 |       3 |       2 |
| 1001 | PM   |     5 |       3 |       2 |
| 1001 | PM   |     5 |       5 |       0 |
| 1002 | PM   |     4 |       2 |       2 |
| 1002 | PM   |     3 |       3 |       0 |
| 1002 | PM   |     1 |       0 |       1 |
+------+------+-------+---------+---------+

我想看到的是这样的:

+------+---------+------+-------+
|  ID  | DayType | Time | Tasks |
+------+---------+------+-------+
| 1001 | Weekday | AM   |     9 |
| 1001 | Weekend | AM   |     7 |
| 1001 | Weekday | PM   |     8 |
| 1001 | Weekend | PM   |     2 |
| 1002 | Weekday | PM   |     5 |
| 1002 | Weekend | PM   |     3 |
+------+---------+------+-------+

我到目前为止最接近的是使用UNION语句,如下所示:

SELECT * FROM
(
    SELECT Weekday, 'Weekday' as 'DayType' FROM t1
    UNION
    SELECT Weekend, 'Weekend' as 'DayType' FROM t1
) AS X

结果如下:

+---------+---------+
| Weekday | DayType |
+---------+---------+
|       2 | Weekend |
|       0 | Weekday |
|       2 | Weekday |
|       0 | Weekend |
|      10 | Weekday |
+---------+---------+

我没有看到任何押韵或理由是什么数字在“工作日”下的数字?专栏,我怀疑他们是以某种方式分组的。当然还有其他几个专栏缺失,但由于我不能在外部查询中放置一个大范围作为内部查询,我无法弄清楚如何将其拉进去。非常感谢帮助

3 个答案:

答案 0 :(得分:2)

您希望union all使用sum()group by id, time的一对汇总查询,一个用于Weekday,一个用于Weekend:< / p>

select Id, DayType = 'Weekend', [time], Tasks=sum(Weekend)
from t
group by id, [time]
union all
select Id, DayType = 'Weekday', [time], Tasks=sum(Weekday)
from t
group by id, [time]

答案 1 :(得分:0)

试试这个

select  ID, 'Weekday' as DayType, Time, sum(Weekday)
from    t1
group by ID, Time
union all
select  ID, 'Weekend', Time, sum(Weekend)
from    t1
group by ID, Time
order by order by 1, 3, 2

答案 2 :(得分:0)

未经测试,但它应该可以解决问题。它可能需要2个proc sql步骤进行计算,一个用于求和,一个用于语句时的情况。如果您有额外的行,只需使用max语句和ID,Time,type_day分组。

Proc sql; create table want as select ID, Time, 
    sum(weekday) as weekdayTask,
    sum(weekend) as weekendTask,
    case when calculated weekdaytask>0 then weekdaytask
        when calculated weekendtask>0 then weekendtask else .
        end as Task,
    case when calculated weekdaytask>0 then "Weekday"
        when calculated weekendtask>0 then "Weekend" 
        end as Day_Type 
from have
group by ID, Time
;quit;

Proc sql; create table want2 as select ID, Time, Day_Type, Task
from want
;quit;