由于子查询导致的INSERT错误

时间:2018-05-17 16:13:15

标签: sql-server tsql

我正在设置一项工作来传输由使用它的程序擦除的一些数据,以便我们可以更长时间地跟踪数据并跟踪它。

我收到此错误:" Column' nextgen.ngprod.dbo.appt_slots.start_date'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。"

但是当我添加该组时,我得到错误:"不能在用于GROUP BY子句列表的表达式中使用聚合或子查询。"

INSERT INTO [Analyst_db].[dbo].[appt_slot_util]
SELECT 
a.start_date,
a.Loc,a.Spec,
a.slots_avail,
a.slots_booked,
a.slots_open
FROM
(
SELECT asl.start_date
        , SUBSTRING(lm.location_name,6,2) as Loc
        , SUBSTRING(lm.location_name,9,3) as Spec
        , SUM(asl.overbook_limit) as slots_avail
        , SUM(asl.appt_count) as slots_booked
        , SUM(asl.overbook_limit)-SUM(asl.appt_count) as slots_open
FROM nextgen.ngprod.dbo.appt_slots asl
    JOIN nextgen.ngprod.dbo.location_mstr lm ON lm.location_id = asl.location_id
) AS a
WHERE NOT EXISTS
(
SELECT * 
FROM [Analyst_db].[dbo].[appt_slot_util] d
WHERE (
        a.start_date=d.start_date and
        a.Loc=d.Loc and
        a.Spec=d.Spec
        )
)

2 个答案:

答案 0 :(得分:1)

您的子查询中似乎缺少一个组:

INSERT INTO [Analyst_db].[dbo].[appt_slot_util]
SELECT 
a.start_date,
a.Loc,a.Spec,
a.slots_avail,
a.slots_booked,
a.slots_open
FROM
(
SELECT asl.start_date
        , SUBSTRING(lm.location_name,6,2) as Loc
        , SUBSTRING(lm.location_name,9,3) as Spec
        , SUM(asl.overbook_limit) as slots_avail
        , SUM(asl.appt_count) as slots_booked
        , SUM(asl.overbook_limit)-SUM(asl.appt_count) as slots_open
FROM nextgen.ngprod.dbo.appt_slots asl
    JOIN nextgen.ngprod.dbo.location_mstr lm ON lm.location_id = asl.location_id
group by asl.start_date
        , SUBSTRING(lm.location_name,6,2) 
        , SUBSTRING(lm.location_name,9,3)  
) AS a
WHERE NOT EXISTS
(
SELECT * 
FROM [Analyst_db].[dbo].[appt_slot_util] d
WHERE (
        a.start_date=d.start_date and
        a.Loc=d.Loc and
        a.Spec=d.Spec
        )
)

答案 1 :(得分:0)

我发现了。我在

中包含了太多的值