SQL多选语句

时间:2013-10-13 07:10:51

标签: sql select case

我目前正在使用select语句以不同的时间间隔使用1个信息亭系统慢慢获取不同成员类别的成员赞助。

SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 09:00' and signout <= '13-10-2013 15:00' and MemberType = 1 and kioskid = 1

SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 15:00' and signout <= '13-10-2013 20:00' and MemberType = 1 and kioskid = 1

SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 09:00' and signout <= '13-10-2013 15:00' and MemberType = 2 and kioskid = 1

SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 15:00' and signout <= '13-10-2013 20:00' and MemberType = 2 and kioskid = 1

我有办法在一个查询中一起抓取数据,如下所示:

                |  09:00 - 15:00  |  15:00 - 20:00
Premium Member  |       21        |       55
Standard Member |       100       |       300

2 个答案:

答案 0 :(得分:0)

是的,你可以这样做:

select * from (
select 'Premium Member' mt, a.cnt "9-15", b.cnt "15-20" from 
(SELECT COUNT(MemberID) cnt from Member where signin >= '13-10-2013 09:00' and signout <= '13-10-2013 15:00' and MemberType = 1 and kioskid = 1) a, ( SELECT COUNT(MemberID) cnt from Member where signin >= '13-10-2013 15:00' and signout <= '13-10-2013 20:00' and MemberType = 1 and kioskid = 1) b
union
select 'Standard Member' mt, c.cnt "9-15", d.cnt "15-20" from 
(SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 09:00' and signout <= '13-10-2013 15:00' and MemberType = 2 and kioskid = 1) c, (SELECT COUNT(MemberID) from Member where signin >= '13-10-2013 15:00' and signout <= '13-10-2013 20:00' and MemberType = 2 and kioskid = 1) d
)

我有硬编码的成员类型,因为我在查询中看不到成员类型ID和成员类型名称之间的任何映射。如果存在这样的映射,则可以替换它。

答案 1 :(得分:0)

您可以使用子查询和分组来执行此操作

select MemberType, 
    COUNT(MemberID in (select MemberID 
                       from Member 
                       where signin >= '13-10-2013 09:00' and signout <= '13-10-2013 15:00')),
    COUNT(MemberID (select MemberID 
                    from Member 
                    where signin >= '13-10-2013 15:00' and signout <= '13-10-2013 20:00')) 
from Member 
group by MemberType