如果这看起来像是一个愚蠢的问题,我会道歉,但它已困扰我好几天了!
我试图运行一个查询来恢复"由"创建的查询数量。在一个非常尴尬的数据库上,我继承了。
到目前为止我所拥有的:
SELECT DISTINCT u.UserCode AS 'Created By',
u.FullName AS 'User Name',
COUNT(DISTINCT(p.PersonCode)) AS 'Qty Created'
FROM dbo.Persons AS p
JOIN dbo.AuditLog AS a
ON p.PersonCode = a.PersonCode
JOIN dbo.Users AS u
ON a.UserCode = u.UserCode
WHERE a.time = p.DateCreated
AND (p.DateCreated AND a.time) BETWEEN '2014-01-01' AND '2014-05-18'
GROUP BY u.UserCode, u.FullName
这只会带回来:
创建者 10000001
用户名管理员
数量创建1
我知道这是错误的,因为当我取出WHERE子句的第二部分时,它会从整个表中返回一个计数,我确定它正在做什么/不做什么,但是任何人都可以指出我正确的方向或提供一些代码作为我的主题描述?
谢谢
Ĵ
答案 0 :(得分:0)
这看起来不对:
AND (p.DateCreated AND a.time) BETWEEN '2014-01-01' AND '2014-05-18'
因为你有:
a.time = p.DateCreated
以下将做:
AND p.DateCreated BETWEEN '2014-01-01' AND '2014-05-18'
答案 1 :(得分:0)
您的BETWEEN
尝试是错误的,并且多余,因为日期必须相同:
变化:
WHERE a.time = p.DateCreated
AND (p.DateCreated AND a.time) BETWEEN '2014-01-01' AND '2014-05-18'
要:
WHERE a.time = p.DateCreated
AND p.DateCreated BETWEEN '2014-01-01' AND '2014-05-18'
注意,如果这些是DATETIME
字段,则BETWEEN
可能会在您使用时返回不需要的结果,因为未指定时的默认时间为00:00:00
。因此,在结束日期的午夜之后的任何时间都将被排除在外。
答案 2 :(得分:0)
如果没有看到样本数据和您想要的输出,很难肯定地说,但是第一件事就是这一行:
AND (p.DateCreated AND a.time) BETWEEN '2014-01-01' AND '2014-05-18'
你想说:
AND p.DateCreated BETWEEN '2014-01-01' AND '2014-05-18'
AND a.time BETWEEN '2014-01-01' AND '2014-05-18'