按查询分组和不按查询分组

时间:2018-12-01 10:27:23

标签: sql sql-server

我对分组和非分组依据有以下查询。但是,我打算检索和使用它们两者,而不必重复查询(其中一个使用分组依据,其中一个未使用分组依据。 ),因为它会影响性能。

以下是查询:

SELECT [People].[FirstName], [People].[LastName], [People].[Age], [People].[RegisterDate], [PeopleGroup].[FirstName] AS PGFirstName, [PeopleGroup].[LastName] AS PGLastName, [PeopleGroup].[Age] AS PGAge
FROM [Game]
OUTER APPLY (
SELECT [FirstName], [LastName], [Age], [RegisterDate] FROM [People]
WHERE [Age] < 20 AND [RegisterDate] BETWEEN '2018-01-01' AND GETDATE()
) AS People
OUTER APPLY (
SELECT [FirstName], [LastName], [Age] FROM [People] AS PeopleGroup
WHERE [Age] < 20 AND [RegisterDate] BETWEEN '2018-01-01' AND GETDATE()
GROUP BY [FirstName], [LastName], [Age]
) PeopleGroup

上面的查询是重复的,因为我已经两次从同一张表中选择了一些东西,这使它与众不同的只是条件,第二个查询使用了group by子句。

关于如何改善上述查询的任何建议?

非常感谢您的回答。

谢谢

1 个答案:

答案 0 :(得分:1)

实际上,您拥有的与此相同,但是,您的目标似乎很奇怪。例如,为什么在数据库中有重复的人?

WITH CTE AS(
    SELECT [FirstName],
           [LastName],
           [Age],
           [RegisterDate]
    FROM [People]
    WHERE [Age] < 20
      AND [RegisterDate] BETWEEN '2018-01-01' AND GETDATE())
SELECT [FirstName],
       [LastName],
       [Age],
       [RegisterDate]
FROM CTE C1
     CROSS APPLY (SELECT DISTINCT
                         [Firstname],
                         [LastName]
                         [Age]
                  FROM CTE) C2;