【问题标题】:How to bring table values into temp table如何将表值带入临时表
【发布时间】: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


【解决方案1】:

您实际上想在此处UNPIVOT -

DECLARE @T TABLE (ScheduledAppts INT, KeptAppts INT, UnkeptAppts INT)

INSERT INTO @T (ScheduledAppts, KeptAppts, UnkeptAppts)
SELECT 30, 20, 10

SELECT [Category]
    ,[Count]
FROM (
    SELECT ScheduledAppts
        ,KeptAppts
        ,UnkeptAppts
    FROM @T
    ) P
UNPIVOT([Count] FOR [Category] IN (
            ScheduledAppts
            ,KeptAppts
            ,UnkeptAppts
            )) AS UnPvt

输出:

Category Count
ScheduledAppts 30
KeptAppts 20
UnkeptAppts 10

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

【讨论】:

    【解决方案2】:

    你可以使用cross apply:

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

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

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2014-02-05
      相关资源
      最近更新 更多