如何将表值带入临时表

时间:2021-05-19 16:27:00

标签: sql-server pivot temp-tables

我有一个 sql 查询,其中 SQL Server 输出数据如下

<头>
ScheduledAppts KeptAppts UnkeptAppts
30 20 10

我想将此输出更改为 sql server #temp 表,使其看起来像这样:

<头>
类别 计数
计划应用 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

2 个答案:

答案 0 :(得分:1)

您实际上想要在此处取消透视 -

            <iframe
              allowFullScreen
              src={videoDetail && videoDetail[0] ? videoDetail[0].videoUrl : ""}
              style={{ border: "none", width: "100%", height: "60vh" }}
              title={
                videoDetail && videoDetail[0]
                  ? videoDetail[0].title
                  : "Default Title"
              }
              onEnded={() => console.log("i want to run a function here.")}
            />

输出:

<头>
类别 计数
计划应用 30
KeptAppts 20
UnkeptAppts 10

参考:Converting Columns into rows with their respective data in sql server

答案 1 :(得分:0)

您可以使用cross apply

select v.*
from output o cross apply
     (values ('ScheduledAppts', ScheduledAppts),
             ('KeptAppts', KeptAppts),
             ('UnkeptAppts', UnkeptAppts)
     ) v(category, count);

注意:如果原始“表”确实是查询结果,您可能会发现更改原始查询更简单。