需要使用 select 子查询查找盈亏计数但没有数据

Need to find count of profit and loss and no data using select subquery

我有以下table

Years Months Credit  Debit  ProfitandLoss Symbol
2019    Jan  10000   2000       1000         P
2019    Aug  8000    1000      -10922        L
2019    May  5000    3000       2000         P
2020    Feb  10000   5000       800          P
2020    Apr  1000    6000        0           N
2020    Oct  2000    1000       2000         P
2021    Jan  6000    8000       -600         L
2021    Mar  2000    3000       1400         P
2021    Nov  2000    2000        0           N

这里我需要计算一个结果中的总贷方、总借方、总盈亏以及盈亏总计、空总计table。

我已经尝试过了,但是无法根据年份获取CountOfProfit、CountOfLoss和CountNothing。

select Years,
      SUM(credit) as [Total Credit],
      SUM(debit) as totaldebit,
      COUNT(Symbol) as totalcredit,
      (select COUNT(Symbol) from Yearly where Symbol='P') as CountofProfit,
      (select  COUNT(Symbol) from Yearly where Symbol='L') as CountofLoss, 
      (select COUNT(Symbol) from Yearly where Symbol='N')as CountNothing
from Yearly 
group by Years 

我的结果table应该是

Years TotalCredit TotalDebit TotalProfitandLoss CountOfProfit CountofLoss CountofNothing
2019   23000       7000       -7022                 2           1             0
2020   13000       12000       2800                 2           0             1         
2021   10000       13000       800                  1           1             1

您需要使用条件聚合。这是通过 CASE 表达式实现的:

SELECT Years,
       SUM(Credit) AS TotalCredit,
       SUM(Debit) AS TotalDebit,
       SUM(ProfitandLoss) AS TotalProfitAndLoss,
       COUNT(CASE Symbol WHEN 'P' THEN 1 END) AS Profits,
       COUNT(CASE Symbol WHEN 'L' THEN 1 END) AS Losses,
       COUNT(CASE Symbol WHEN 'N' THEN 1 END) AS Nothings
FROM (VALUES(2019,'Jan',10000,2000, 1000 ,'P'),
            (2019,'Aug',8000 ,1000,-10922,'L'),
            (2019,'May',5000 ,3000, 2000 ,'P'),
            (2020,'Feb',10000,5000, 800  ,'P'),
            (2020,'Apr',1000 ,6000,  0   ,'N'),
            (2020,'Oct',2000 ,1000, 2000 ,'P'),
            (2021,'Jan',6000 ,8000, -600 ,'L'),
            (2021,'Mar',2000 ,3000, 1400 ,'P'),
            (2021,'Nov',2000 ,2000,  0   ,'N'))V(Years,Months,Credit,Debit,ProfitandLoss,Symbol)
GROUP BY Years
ORDER BY Years;