0

我有这样的 SQL:

SELECT 
Mid(Note, 
  InStr(Note, "device.")-
  (
   InStr(Note, "device.")-
   InStr(Note, "pressure and")
  )
  +13,
  (InStr(Note, "device.") - InStr(Note, "pressure and")) - 14
  )
  AS [Device],
  Count([Device]),
Date_Field & " " & Time_Field AS [DateTime],
EnteredBy
FROM MyLog
WHERE Note LIKE "*removed and*"
GROUP BY [Device]
ORDER BY Date_Field DESC
;

我想要GROUP BY那个自定义字段[Device]并计算每个设备有多少。但是上面的代码为“... AS [Device]”部分给出了错误“...不包括指定的表达式...作为聚合函数的一部分”。

我怎样才能做到这一点?

现在数据看起来像:

Record1      12/05/12 03:02:12    User2
Record1      12/02/12 01:02:12    User1
Record1      12/01/12 02:02:12    User2
Record2      12/06/12 03:02:12    User2
Record2      12/07/12 03:02:12    User3

但我希望它看起来像:

Record1    3
Record2    2

这是有效的旧 SQL(不聚合):

SELECT Mid(Note, 
  InStr(Note, "device.")-
  (
   InStr(Note, "device.")-
   InStr(Note, "pressure and")
  )
  +13,
  (InStr(Note, "device.") - InStr(Note, "pressure and")) - 14
  ) AS Device, Date_Field & " " & Time_Field AS [DateTime], EnteredBy
FROM MyLog
WHERE Note LIKE "*removed and*"
ORDER BY Date_Field DESC;
4

3 回答 3

1

您不能在 MS Access 的 GROUP BY 中引用别名设备,但您可以创建一个子查询并从中引用别名。

这对我来说是:

SELECT EnteredBy, Device, Count(Device) As CountDev FROM (
SELECT 
Mid(Note,InStr(Note,"device.")-
         (InStr(Note,"device.")-
          InStr(Note,"pressure and"))+13,
    (InStr(Note,"device.")-InStr(Note,"pressure and"))-14) AS Device, 
MyLog.EnteredBy
FROM MyLog
WHERE MyLog.[Note] Like "*removed and*")
GROUP BY EnteredBy, Device
于 2013-01-23T17:46:41.800 回答
1

您收到该错误是因为 Device 不是列。也许您可以使用子查询,尽管我承认有一段时间没有使用 Access。

尝试这样的事情:

SELECT Count([Device]), Device, [DateTime], EnteredBy
FROM (
SELECT
Mid(Note, 
  InStr(Note, "device.")-
  (
   InStr(Note, "device.")-
   InStr(Note, "pressure and")
  )
  +13,
  (InStr(Note, "device.") - InStr(Note, "pressure and")) - 14
  )
  AS [Device],
  Date_Field & " " & Time_Field AS [DateTime],
  EnteredBy
FROM MyLog
WHERE Note LIKE "*removed and*" ) t
GROUP BY Device, [DateTime], EnteredBy
ORDER BY Date_Field DESC
;

祝你好运。

于 2013-01-23T17:48:38.083 回答
0

与此类似的东西 - 基本上将复杂部分嵌套到子查询中。

select dev, count(dev) from
(
SELECT 
Mid(Note, 
  InStr(Note, "device.")-
  (
   InStr(Note, "device.")-
   InStr(Note, "pressure and")
  )
  +13,
  (InStr(Note, "device.") - InStr(Note, "pressure and")) - 14
  )
  AS dev,
Date_Field & " " & Time_Field AS DateTime,
EnteredBy
FROM MyLog
WHERE Note LIKE "*removed and*"
)
GROUP BY dev
ORDER BY DateTime DESC
于 2013-01-23T17:47:21.673 回答