两个weeknum列的SQL摘要

时间:2016-12-16 15:33:04

标签: sql

是否可以编写SQL查询以获取下面的摘要结果..?

表格预览:

UniqueID     StartWk     FinishWk
ID000001     2016|49     2016|49
ID000002     2016|49     2016|50
ID000003     2016|49     NULL
ID000004     2016|49     2016|50
ID000005     2016|49     2016|50
ID000006     2016|50     NULL
ID000007     2016|50     NULL
ID000008     2016|50     2016|50
ID000009     2016|50     2016|51

摘要输出:

Week         Started     Finished
2016|49      5           1
2016|50      4           4
2016|51      0           1

3 个答案:

答案 0 :(得分:1)

这是一种方法,但我认为它不是最有效的方法。

首先,我们需要一整周的一整套,因为您可以在数据中有一个完成周,或者反之亦然。

然后我们只使用一个查询来选择每周值的计数。

SELECT A.week
    , (SELECT count(1) FROM table B WHERE B.StartWk = A.Week) as Started
    , (SELECT count(1) FROM table C WHERE C.FinishWk= A.Week) as Finished

FROM (SELECT startWk as Week FROM Table WHERE startWk is not null UNION 
      SELECT FinishWk as Week FROM Table WHERE FinishWk is not null
      ) A

这可能更有效率,因为它能够每周获得一次计数,而不必在合并的几周内每周执行2次查询。

SELECT A.Week, B.Started, C.Finished
FROM (SELECT startWk as Week FROM Table WHERE startWk is not null UNION 
      SELECT FinishWk as Week FROM Table WHERE FinishWk is not null) A
LEFT JOIN (SELECT startWk, count(1) Started
           FROM TABLE
           GROUP BY StartWk) B
  ON A.Week = B.startWk
LEFT JOIN (SELECT FinishWk, count(1) Finished
           FROM TABLE
           GROUP BY FinishWk) C
  ON A.Week = C.FinishWk

答案 1 :(得分:1)

如果您的DBMS符合ANSI标准,则以下内容适用于您:

select
    coalesce(a.week, b.week) week,
    coalesce(a.cnt, 0) started,
    coalesce(b.cnt, 0) finished
from 
    (select startwk week, count(1) cnt from t where startwk is not null group by startwk) a
full outer join
(select finishwk week, count(1) cnt from t where finishwk is not null group by finishwk) b
on a.week = b.week
order by week;

答案 2 :(得分:0)

使用xQbert Query我正在更新如下的查询。

SELECT 
    A.`Week`, 
    COALESCE(B.Started,0)Started, 
    COALESCE(C.Finished,0)Finished
FROM (SELECT StartWk as `Week` FROM my_table_name UNION 
      SELECT FinishWk as `Week` FROM my_table_name ) A
LEFT JOIN (SELECT startWk, count(1) Started
           FROM my_table_name
           GROUP BY StartWk) B
  ON A.`Week` = B.StartWk
LEFT JOIN (SELECT FinishWk, count(1) Finished
           FROM my_table_name
           GROUP BY FinishWk) C
  ON A.`Week` = C.FinishWk
WHERE TRIM(A.`Week`) != ''
ORDER BY A.`Week`;

SQL Fiddle Demo

<强>输出:

enter image description here