表1列出了客户,客户拥有的成员身份,使用的服务以及使用服务的日期
表2只是表1,按月和会员类型分组,然后是服务会话数
我想做的是仅按特定的服务类型来统计会员会话。到目前为止,这是我所拥有的,它返回一个错误,指出“ Service_Type”不在聚合函数或group by子句中,当我将“ Service_Type”放入group by中时,查询没有错误,但SESSIONS列全为NULL
SELECT
DATEFROMPARTS(YEAR(t1.Date),MONTH(t1.Date),1)AS 'Draft_Date',
Membership,
CASE
WHEN Membership = 5 AND Service_Type = 'A' THEN COUNT(*)
WHEN Membership = 2 AND Service_Type IN ('J','C')
END AS'SESSIONS'
FROM Table1 t1
GROUP BY DATEFROMPARTS(YEAR(t1.Date),MONTH(t1.Date),1),Membership
case语句将包括所有成员资格和服务类型,但是我认为这足以满足我的示例要求。任何帮助将不胜感激!我已经参加了好几天了。
答案 0 :(得分:0)
使用总金额
SELECT DATEFROMPARTS(YEAR(t1.Date),MONTH(t1.Date),1) AS Draft_Date , Membership,
sum(CASE WHEN Membership = 5 AND Service_Type = 'A' THEN 1 else 0 end),
sum(case WHEN Membership = 2 AND Service_Type IN ('J','C') then 1 else 0 end)
FROM Table1 t1 group by DATEFROMPARTS(YEAR(t1.Date),MONTH(t1.Date),1)
答案 1 :(得分:0)
您快到了!我做了一些更改:
SELECT
DATEFROMPARTS(YEAR(t1.Date), MONTH(t1.Date),1) AS Draft_Date,
Membership,
COUNT(CASE WHEN t1.Membership = 5 AND t1.Service_Type = 'A' THEN 1 END) as m5stA,
COUNT(CASE WHEN t1.Membership = 2 AND t1.Service_Type IN ('J','C') THEN 1 END) as m2stJC
FROM Table1 t1
GROUP BY YEAR(t1.Date), MONTH(t1.Date), Membership
更改: