Sql 将一列中的值实例求和到不同的列中

Sql 将一列中的值实例求和到不同的列中,sql,self-join,Sql,Self Join,我有一个表session,其中有一个appointmentType列(nvarchar)。aptType可以是三个值(小时、半小时、成对)之一 我需要的是clientname,小时数,半小时数,配对数 所以数据可能是这样的 bob | Hour bob | Hour bob | halfhour bob | halfhour bob | halfhour bob | Pair 我想要的是 bob | 2 | 3 | 1 我试过这个主题的变奏曲 select c.firstname, coun

我有一个表session,其中有一个appointmentType列(nvarchar)。aptType可以是三个值(小时、半小时、成对)之一

我需要的是clientname,小时数,半小时数,配对数

所以数据可能是这样的

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个小时的apt类型,其余的为0

当我做以上的事情时,我得到了

bob | 1135 | 1135 | 1135
如果我将where改为an或返回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

这可以使用单个联接完成,您可以使用带有聚合函数的
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 |

非常好,我喜欢。你一秒钟前有两个版本,第二个版本与我的版本完全相同,只是你的版本与我的版本不同。非常令人沮丧。不管怎样,谢谢。@Raif当我测试join版本时,它并没有完全正常工作。因此,我删除了它以包含一个
PIVOT
版本。