![](/img/trans.png)
[英]How do I combine two SQL Queries, and uniquely label each in my output?
[英]How label each output group type
我有這樣的查詢:
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
我如何將其設置為 label 個人 output 格式如下(每個 output 行前面都有 overall_count 文本):
overall_count 2 2022/12
overall_count 1 2022/12
我在搜索 inte.net 時找不到有關如何執行此操作的任何信息。 這將幫助使用該報告的人進行計算。
concat()
非常適合這里。
順便說一句, format()
有一些很棒的特性,但性能很糟糕(應該謹慎使用)。 請注意,我改用convert(varchar(7),datefulfilled,111)
更新:使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.