两列日期和聚合

时间:2018-03-14 17:23:34

标签: sql

我有这个问题:

SELECT 
    Identified_Date, 
    Referred_Date, 
    count(IdentifiedmemberID) as id_volume, 
    count(ReferredMemberID) as refer_volume
FROM MyTable

它返回如下列表:

Identified_Date  Referred_Date  id_volume  refer_volume

2/7/18           2/7/18         2          10

2/14/18          2/21/18        8          4

我怎样才能将日期排成一行,以便如果匹配日期匹配,则匹配日期。 OR(理想情况下)将两个日期列组合在一起,如下所示:

Date  id_volume  refer_volume

2/7/18     2          10

2/14/18    8          0

2/21/18    0          4

1 个答案:

答案 0 :(得分:0)

您可以使用以下SQL语句来完成您的要求。

Select Temp.Common_Date, Max(Temp.id_volume) As id_volume, Max(Temp.refer_volume) As refer_volume
From
(       
    Select MT.Identified_Date As Common_Date, count(IdentifiedmemberID) as id_volume, 0 As refer_volume
    From MyTable MT

    UNION

    Select MT.Referred_Date As Common_Date, 0 As id_volume, count(ReferredMemberID) as refer_volume
    From MyTable MT
)Temp
group by Common_Date

如果有任何问题,请告诉我!