SQL Server 如何标记每个输出组类型

arknldoa  于 2023-01-12  发布在  其他
关注(0)|答案(1)|浏览(111)

我有这样一个疑问:

Product

orderid  TypeId datefulfilled
17749    Spec   2022-10-11 18:35:25.000
17754    Spec   2022-10-12 18:35:25.000
17755    Spec   2022-10-12 18:35:25.000
17756    Spec   2022-10-12 18:35:25.000
17757    Spec   2022-10-16 18:35:25.000
17769    Spec   2022-11-24 18:35:25.000
17788    Spec   2022-12-12 18:35:25.000
17819    Spec   2022-12-19 18:35:25.000
17829    Spec   2022-12-19 18:35:25.000
17830    Spec   2022-01-08 18:35:25.000
17830    Cert   2022-01-08 18:35:25.000

select  
  count(distinct p.orderid) as overall_count, format(datefulfilled, 'yyyy/MM')
from Product p where datefulfilled <= dateadd(year,-1,getdate()) and typeId in ('Spec') group by format(datefulfilled,'yyyy/MM') order by format(datefulfilled,'yyyy/MM')

给出如下结果计数:

overall_count
2  2022/12
1  2023/01

我如何让它标记格式如下的单个输出(每个输出行前面都有overall_count文本):

overall_count 2  2022/12
overall_count 1  2022/12

我在网上找不到任何关于如何做这件事的信息。这将有助于人们使用报告做他们的计算。

qni6mghb

qni6mghb1#

concat()很适合这里。
顺便说一句,format()有一些很棒的特性,但是性能很糟糕(应该少用它)。

    • 更新日期**:我使用CROSS APPLY来减少日期转换的次数
    • 示例**
select NewValue = concat('overall_count'
                         ,
                          ' '
                         ,
                          count(distinct p.orderid)
                         ,' '
                         ,yyyymm
                        )
from Product p 
cross apply ( values ( convert(varchar(7),datefulfilled,111) ) ) b(yyyymm) 
where datefulfilled <= dateadd(year,-1,getdate()) 
  and typeId in ('Spec') 
  group by yyyymm
  order by yyyymm
    • 结果**
NewValue
overall_count 1 2022/01

相关问题