首先,我的sql最多是粗暴的,所以请光临我。
我有一个表session,其中有一个appointmentType列(nvarchar)。 aptType可以是三个值之一(小时,半小时,对)。
我需要的是客户名称,小时数,半小时数,对数。
所以数据可能看起来像这样
bob | Hour
bob | Hour
bob | halfhour
bob | halfhour
bob | halfhour
bob | Pair
我想要的是
bob | 2 | 3 | 1
我试过这个主题的变体
select c.firstname,
count(shour.clientid),
count(shalfhour.clientid),
count(sHour.clientid)
From Client as c
left outer join [session] as sHour on c.Entityid = shour.ClientId
left outer join [session] as sHalfHour on c.Entityid = sHalfHour.ClientId
left outer join [session] as sPair on c.Entityid = sPair.ClientId
where c.entityid =1 and (shour.appointmentType = 'Hour' or sHalfHour.appointmentType = 'HalfHour')
group by c.firstname
客户1的数据是他有35小时的apttypes,其余为0。
当我这样做时,我得到了
bob | 1135 | 1135 | 1135
如果我将where更改为a或者我将0行返回。
无论如何要做我想做的事情?
谢谢, [R
答案 0 :(得分:2)
这可以使用单个连接完成,并使用带有聚合函数的CASE
语句来转动数据:
select c.firstname,
SUM(case when s.appointmentType = 'Hour' then 1 else 0 end) Hour,
SUM(case when s.appointmentType = 'HalfHour' then 1 else 0 end) HalfHour,
SUM(case when s.appointmentType = 'Pair' then 1 else 0 end) Pair
From Client as c
left outer join [session] as s
on c.Entityid = s.ClientId
where c.entityid =1
group by c.firstname;
您没有指定RDBMS,但如果您使用的是具有PIVOT
功能的数据库(Oracle 11g +,SQL Server 2005+),那么您的查询将如下所示:
select firstname, Hour, HalfHour, Pair
from
(
select c.firstname, s.appointmentType
from Client as c
left outer join [session] as s
on c.Entityid = s.ClientId
where c.entityid =1
) src
pivot
(
count(appointmentType)
for appointmentType in (Hour, HalfHour, Pair)
) piv
两个查询的结果是:
| FIRSTNAME | HOUR | HALFHOUR | PAIR |
--------------------------------------
| Bob | 2 | 3 | 1 |
答案 1 :(得分:0)
您只能计算您的组定义的内容,因此返回计数的最佳方式是单独的行,而不是一行中的所有行。换句话说,这个:
bob | Hour | 2
bob | halfhour | 3
bob | Pair | 1
而不是:
bob | 2 | 3 | 1
所以查询看起来像:
SELECT
c.firstname,
c.Entityid,
count(c.clientid) as ct
FROM Client as c
GROUP BY c.firstname, c.Entityid
一旦将它们作为单独的行获取,您可以“旋转”该表以将它们全部组合成一行,如果您确实需要的话。如果您具有灵活性,也可以在应用程序级别执行此操作。沿着这些方向做的事情应该做到,而不是实际测试,所以希望它接近:
SELECT
t.firstname,
SUM(CASE(t.Entityid WHEN 'hour' THEN t.ct ELSE 0)) as hour,
SUM(CASE(t.Entityid WHEN 'halfhour' THEN t.ct ELSE 0)) as halfhour,
SUM(CASE(t.Entityid WHEN 'Pair' THEN t.ct ELSE 0)) as Pair
FROM (
SELECT
c.firstname,
c.Entityid,
count(c.clientid) as ct
FROM Client as c
GROUP BY c.firstname, c.Entityid
) t
GROUP BY t.firstname