1

UNION我想从查询中找出行数。

我试过这个:

SELECT COUNT(*) FROM (
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID)
   FROM [Laola].[AGG_0] 
   GROUP BY Platform, DeviceCategory
   UNION
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) 
   FROM [Laola].[AGG_2] 
   GROUP BY Platform, DeviceCategory
) x

我收到以下错误:

没有为第 3 列指定列x

4

4 回答 4

3

您需要为正在应用 COUNT 计算的列指定名称。

SELECT COUNT(*) FROM (
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) Count
   FROM [Laola].[AGG_0] 
   GROUP BY Platform, DeviceCategory
   UNION
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) 
   FROM [Laola].[AGG_2] 
   GROUP BY Platform, DeviceCategory
) x
于 2017-10-11T15:40:01.170 回答
2

您需要给第三列一个别名:

SELECT COUNT(*) FROM (
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) As Count
   FROM [Laola].[AGG_0] 
   GROUP BY Platform, DeviceCategory
   UNION
   SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) As Count
   FROM [Laola].[AGG_2] 
   GROUP BY Platform, DeviceCategory
) x
于 2017-10-11T15:39:50.140 回答
1

您只需要该列的别名:

SELECT COUNT(*) 
FROM (
       SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) as nr
       FROM [Laola].[AGG_0] 
       GROUP BY Platform, DeviceCategory
       UNION
       SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) 
       FROM [Laola].[AGG_2] 
       GROUP BY Platform, DeviceCategory
    ) x
于 2017-10-11T15:39:53.940 回答
1

不要UNION查询!它删除重复项。使用UNION ALL.

下面给出了行数和每个表中唯一计数的总和:

SELECT COUNT(*), SUM(cnt)
FROM ((SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) as cnt
       FROM [Laola].[AGG_0] 
       GROUP BY Platform, DeviceCategory
      ) UNION ALL
      (SELECT Platform, DeviceCategory, COUNT(DISTINCT FullVisitorID) as cnt
       FROM [Laola].[AGG_2] 
       GROUP BY Platform, DeviceCategory
      )
     ) x;

如果您不使用COUNT(DISTINCT),则将其从子查询中删除。它会产生开销,我不能 100% 确定优化器会删除它。

从准确性、简洁性和效率的角度来看,我建议:

SELECT COUNT(*)
FROM ((SELECT DISTINCT Platform, DeviceCategory
       FROM [Laola].[AGG_0] 
      ) UNION ALL
      (SELECT DISTINCT Platform, DeviceCategory
       FROM [Laola].[AGG_2] 
      )
     ) x;
于 2017-10-11T15:45:58.647 回答