【发布时间】:2021-05-19 16:27:00
【问题描述】:
我有一个 sql 查询,其中 SQL Server 输出数据如下所示
| ScheduledAppts | KeptAppts | UnkeptAppts |
|---|---|---|
| 30 | 20 | 10 |
我想将此输出更改为 sql server #temp 表,如下所示:
| Category | Count |
|---|---|
| ScheduledAppts | 30 |
| KeptAppts | 20 |
| UnkeptAppts | 10 |
一直在尝试使用 Pivot,但我认为我做错了。
代码:
SELECT
COUNT(x.Scheduled) AS ScheduledAppts,
COUNT(x.KeptEncounters) AS KeptAppts,
COUNT(x.UnkeptEncounters) AS UnkeptAppts
FROM (
SELECT DISTINCT
COUNT(frz.TotalAppt) AS Scheduled,
CASE
WHEN frz.PDEncounters > 0 THEN
COUNT(frz.PDEncounters)
END AS KeptEncounters,
CASE
WHEN frz.PDEncounters = 0 THEN
COUNT(frz.PDEncounters)
END AS UnkeptEncounters,
FROM [CDW].[dbo].[Fact_FREEZEPOLICE] frz
) x
【问题讨论】:
-
关于临时表的具体点.. 也看看 CTE 的。 (公用表表达式)- 使用
with子句通常会抓痒! ;-)
标签: sql-server pivot temp-tables