在SQL Server 2008中,此查询有效:
SELECT
SUM(CAST(isredeemed AS TINYINT)) AS totalredeemed,
FROM rewards
GROUP BY merchantid
它为您提供商家兑换奖励的数量。 TINYINT
强制转换需要避免错误Operand data type bit is invalid for sum operator.
现在我想做一个类似的查询,但只能查找过去几天兑换的奖励。我试过这个:
SELECT
SUM(CAST((isredeemed & ( MIN(dateredeemed) > '2014-01-10 05:00:00')) AS TINYINT)) AS claimedthisweek,
FROM rewards
GROUP BY merchantid
我收到了错误
'>'附近的语法不正确。
我还尝试用&
和&&
替换AND
。但那些也不起作用。
如何使示例有效?
答案 0 :(得分:1)
这个问题缺乏细节来给出确切的答案,但您需要使用派生表或子查询进行计算。
类似这样的事情
SELECT r1.merchantid, r2.claimedthisweek
FROM rewards r1
JOIN (
SELECT merchantid, SUM(CAST(isredeemed AS INT)) claimedthisweek
FROM rewards
GROUP BY merchantid
HAVING MIN(dateredeemed) > '20140101'
) r2
答案 1 :(得分:0)
我认为你希望这会有效,但它会算两次:
SELECT
SUM(case when MIN(dateredeemed) > '2014-01-10 05:00:00' then 1 else 0 end )
FROM rewards
GROUP BY merchantid
答案 2 :(得分:0)
这应该在having子句上,如下所示:
SELECT
SUM(CAST((isredeemed AS TINYINT)) AS claimedthisweek
FROM rewards
GROUP BY merchantid
HAVING MIN(dateredeemed) > '2014-01-10 05:00:00'
答案 3 :(得分:0)
有什么理由不在“where”子句级别进行过滤?只要您聚合的所有行都符合相同的条件,这应该有效:
SELECT
SUM(CAST(isredeemed AS TINYINT)) AS claimedthisweek
FROM rewards
WHERE dateredeemed > '2014-01-10 05:00:00'
GROUP BY merchantid