我可能在这里遗漏了一些简单的东西。我有第一张表:
CREATE TABLE [Orgnzs] (
[id] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
[nm] NVARCHAR(256)
);
然后还有几个表都是这样创建的(都具有相同的结构):
-- WLog_* tables are all created as such
CREATE TABLE [WLog_1] (
[id] BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY,
[huid] UNIQUEIDENTIFIER,
[dtin] BIGINT,
[dtout] BIGINT,
[cnm] NVARCHAR(15),
[batt] TINYINT,
[pwrop] TINYINT,
[pst] INT,
[flgs] INT,
[ppocs] NVARCHAR(1024),
[ppocu] NVARCHAR(1024),
[por] NVARCHAR(1024)
);
和一组类似的表,没有上表中的最后3列:
-- ULog_* tables are all created as such
CREATE TABLE [ULog_1] (
[id] BIGINT NOT NULL IDENTITY(1,1) PRIMARY KEY,
[huid] UNIQUEIDENTIFIER,
[dtin] BIGINT,
[dtout] BIGINT,
[cnm] NVARCHAR(15),
[batt] TINYINT,
[pwrop] TINYINT,
[pst] INT,
[flgs] INT
);
我的目标是从任意一组WLog_ *和ULog_ *表中选择记录,并通过可管理的元素数量(用于页面布局)限制它,我还需要知道找到的记录总数。
所以我这样选择:
SELECT b.[id] AS evtID,
b.[huid] as huid,
b.[dtin] as dtin,
b.[dtout] as dtout,
b.[cnm] as cnm,
b.[batt] as batt,
b.[pwrop] as pwrop,
b.[pst] as pst,
b.[flgs] as flgs,
b.[ppocs] as ppocs,
b.[ppocu] as ppocu,
b.[por] as por,
b.[orgID] as orgID,
b.[wLg] as wLg,
orgz.[nm] as orgNm
, COUNT_BIG(*) as allRecordsFound
FROM (
-- next also specify the column(s) to sort by
SELECT *, ROW_NUMBER() OVER (ORDER BY [dtin], [cnm] ASC) AS rw FROM (
SELECT *, 1 AS orgID, 1 AS wLg
FROM [WLog_1]
UNION ALL
SELECT *, 2 AS orgID, 1 AS wLg
FROM [WLog_2]
UNION ALL
SELECT *, NULL AS [ppocs], NULL AS [ppocu], NULL AS [por], 1 AS orgID, 0 AS wLg
FROM [ULog_1]
) a
WHERE [pst]&1=1 OR [pst]=67
) b
LEFT JOIN [Orgnzs] AS orgz ON orgID=orgz.[id]
WHERE rw >= 2 AND rw <= 4 -- restrict for a page only
,遗憾的是COUNT_BIG(*) as allRecordsFound
行失败,出现以下错误:
专栏&#39; b.id&#39;在选择列表中无效,因为它不是 包含在聚合函数或GROUP BY子句中。
我还没有使用SQL Server一段时间,有人可以建议我在这里缺少什么吗?
PS。出于测试目的,我made a Fiddle尝试一下。
答案 0 :(得分:2)
请改用:
count(*) over() as allRecordsFound
您可以在select语句中混合窗口聚合函数,而不用分组。