将两个 SQL 选择合并为一个结果
Merge two SQL selects into one result
在同一个 table 上有两个 SQL select。 1st select 显示所需的用户数据。 2nd select 查找使用了多少次 "initials"。该值往往会被多次使用,尽管它不应该
我不想像查询 1 那样减少行数,而是添加 "Initial Count on all"
-- 显示所有所需数据的第一个查询
SELECT
UserID, Username, Initials
FROM
dbo.Users
此查询可以计算首字母
SELECT
Initials, count(*) as InitialCount
FROM
dbo.Users
GROUP BY
Initials
输出:
UserID | Username | Initals | Initialcount
----------------------------------------------
1 | Peter Pan | PP | 2
2 | Paul Pax | PP | 2
3 | John Doe | JD | 1
您可以使用 COUNT()
和 OVER()
来获取每个组的计数(由 PARTITION BY
定义),而不需要 GROUP BY
:
SELECT
UserID
, Username
, Initials
, COUNT(*) OVER(PARTITION BY Initials) AS InitialCount
FROM
dbo.Users
通常称为解析函数或 window 函数,OVER()
可与 MIN()
、MAX()
、SUM()
等聚合函数一起使用。
SELECT UserID, Username, Inititials,
(SELECT COUNT(*) FROM dbo.Users U2 WHERE U2.Inititals = U1.Initials) InitialCount
FROM dbo.Users U1
因此,请尝试使用关键字 distinct,具体取决于您可能需要进行自连接的数据。我刚刚学习 SQL 所以我可能不正确。
SELECT DISTINCT UserID, Username, Initials, count(Initials) as InitialCount
FROM dbo.Users
GROUOP BY UserID
在同一个 table 上有两个 SQL select。 1st select 显示所需的用户数据。 2nd select 查找使用了多少次 "initials"。该值往往会被多次使用,尽管它不应该
我不想像查询 1 那样减少行数,而是添加 "Initial Count on all"
-- 显示所有所需数据的第一个查询
SELECT
UserID, Username, Initials
FROM
dbo.Users
此查询可以计算首字母
SELECT
Initials, count(*) as InitialCount
FROM
dbo.Users
GROUP BY
Initials
输出:
UserID | Username | Initals | Initialcount
----------------------------------------------
1 | Peter Pan | PP | 2
2 | Paul Pax | PP | 2
3 | John Doe | JD | 1
您可以使用 COUNT()
和 OVER()
来获取每个组的计数(由 PARTITION BY
定义),而不需要 GROUP BY
:
SELECT
UserID
, Username
, Initials
, COUNT(*) OVER(PARTITION BY Initials) AS InitialCount
FROM
dbo.Users
通常称为解析函数或 window 函数,OVER()
可与 MIN()
、MAX()
、SUM()
等聚合函数一起使用。
SELECT UserID, Username, Inititials,
(SELECT COUNT(*) FROM dbo.Users U2 WHERE U2.Inititals = U1.Initials) InitialCount
FROM dbo.Users U1
因此,请尝试使用关键字 distinct,具体取决于您可能需要进行自连接的数据。我刚刚学习 SQL 所以我可能不正确。
SELECT DISTINCT UserID, Username, Initials, count(Initials) as InitialCount
FROM dbo.Users
GROUOP BY UserID