1

我有一个表会话,其中有一个约会类型列(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 更改为 an 或返回 0 行。

反正有什么我想做的吗?

4

2 回答 2

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;

请参阅带有演示的 SQL Fiddle

您没有指定什么 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

请参阅带有演示的 SQL Fiddle

两个查询的结果是:

| FIRSTNAME | HOUR | HALFHOUR | PAIR |
--------------------------------------
|       Bob |    2 |        3 |    1 |
于 2013-01-07T17:30:14.030 回答
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
于 2013-01-07T17:26:59.253 回答