在SQL中计算总数

时间:2018-11-15 11:27:33

标签: sql sql-server tsql

我有一个下表,我想获取发给每个理事会的票数。

      Title    No_ticket    Directorate1     Direcotorate2  Direcotorate3    Direcotorate4   Direcotorate5 
   Conference   2           Marketing            Finance
      Training  2               IT               Finance
      Training  2               IT               Marketing

我希望将输出显示为

 Directorate  Total ticket 
  Marketing       2
    IT            2
   Finance        2

我该如何做到这一点。任何帮助,将不胜感激。

我的脚本是

select Count(t.no_ticket),directorate1 
from #ticketbooking t
group by t.no_ticket,directorate1

union

select Count(t.no_ticket),directorate2 
from #ticketbooking t
group by t.no_ticket,directorate2

没有给我我想要的东西

3 个答案:

答案 0 :(得分:3)

您可以尝试使用全部合并和子查询

CREATE INDEX ht_recdate_idx on mybucket(recdate, ht)

答案 1 :(得分:3)

在对其他问题的评论中,您声明每个理事会仅获得一张票,并且实际上有五个理事会专栏。

我要 假定 ,如果没有第五局,则该列包含一个NULL。这使我进入下面的查询中的WHERE子句。

SELECT
    Directorate, COUNT(*) AS ticket_allocation
FROM
(
    SELECT directorate1 AS directorate FROM yourTable WHERE directorate1 IS NOT NULL
    UNION ALL
    SELECT directorate2 AS directorate FROM yourTable WHERE directorate2 IS NOT NULL
    UNION ALL
    SELECT directorate3 AS directorate FROM yourTable WHERE directorate3 IS NOT NULL
    UNION ALL
    SELECT directorate4 AS directorate FROM yourTable WHERE directorate4 IS NOT NULL
    UNION ALL
    SELECT directorate5 AS directorate FROM yourTable WHERE directorate5 IS NOT NULL
)
    AS pivotted
GROUP BY
    directorate

或者...

SELECT
    pivotted.directorate, COUNT(*) AS ticket_allocation
FROM
    yourTable
CROSS APPLY
(
    SELECT yourTable.directorate1 WHERE yourTable.directorate1 IS NOT NULL  
    UNION ALL
    SELECT yourTable.directorate2 WHERE yourTable.directorate2 IS NOT NULL  
    UNION ALL
    SELECT yourTable.directorate3 WHERE yourTable.directorate3 IS NOT NULL  
    UNION ALL
    SELECT yourTable.directorate4 WHERE yourTable.directorate4 IS NOT NULL  
    UNION ALL
    SELECT yourTable.directorate5 WHERE yourTable.directorate5 IS NOT NULL  
)
    AS pivotted(directorate)
GROUP BY
    pivotted.directorate

答案 2 :(得分:0)

我建议使用cross apply

select v.directorate, Count(t.no_ticket) as total_tickets
from #ticketbooking t cross apply
     (values (t.directorate1), (t.directorate2)) v(directorate)
where v.directorate is not null
group by v.directorate;