来自印度尼西亚的Fajar,我有问题用sql server创建报告。 我有一个交易表,如下所示,
Date | Trx_ID| Member_id| Invt_id |Branch_id 01-01-2013 | tr001 | 0002 | invt002 |br001 01-01-2013 | tr001 | 0002 | invt003 |br001 01-01-2013 | tr001 | 0002 | invt004 |br001 01-03-2013 | tr002 | 0001 | invt001 |br001 01-03-2013 | tr002 | 0001 | invt003 |br001 01-04-2013 | tr003 | 0003 | invt002 |br001 01-04-2013 | tr003 | 0003 | invt004 |br001 01-05-2013 | tr004 | 0002 | invt005 |br001 01-05-2013 | tr004 | 0002 | invt006 |br001 01-05-2013 | tr005 | 0005 | invt004 |br001 01-05-2013 | tr005 | 0005 | invt005 |br001 01-05-2013 | tr005 | 0005 | invt006 |br001 01-06-2013 | tr006 | 0001 | invt001 |br001 01-06-2013 | tr006 | 0001 | invt002 |br001
我希望像这样创建报告
Branch_id| weekdays | weekend|weekdays_Weekend br001 | 2 | 1 | 2
由member_id表示的平均组。如果在周末进行交易的会员在工作日计算,如果在工作日进行交易的会员在周末也计算它,但如果在平日和周末进行交易的会员在工作日_周末计算它。 周末是:周六和周日 工作日是:周一,周二,周三,周四和周五 weekdays_weekend如果成员执行的交易超过1并且在周末和工作日进行
当我尝试
时这是错误的查询select max(branch_id) , count(DISTINCT trx_id) , sum(case when datename(dw,date) in ('Monday','Tuesday','Wednesday','Thursday','Friday') then f.trx_id else null end) AS 'WeekDays' , sum(case when datename(dw,date) in ('Saturday', 'Sunday') then 1 else 0 end) as 'Weekend' , sum(case when datename(dw,date) in ('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday') then 1 else 0 end) as 'Weekdays_weekend' from Transaction where branch_id = '14067' and convert (char(6), date, 112) = '201301' group by branch_id
结果不是包含trx_id和member_id
的组Branch_id|weekdays|weekend|weekdays_weekend br001 | 7 | 7 | 0如果我的英语不好,我很抱歉 请帮我创建报告
答案 0 :(得分:0)
嗯,我不能通过计算工作日_周末来了解你的情况,但是bewlow是查询周末或工作日的总交易
SELECT branch_id,
SUM(CASE WHEN DATEPART(dw,[Date]) NOT IN (1,7) THEN 1 ELSE 0 END) as weekdays,
SUM(CASE WHEN DATEPART(dw,[Date]) IN (1,7) THEN 1 ELSE 0 END) as weekend
FROM tableName
GROUP BY branch_id
DATEPART()函数提取dw传递给它的星期几。返回的值是1到7,星期六是7,星期日是1