我正在尝试生成一个包含3列的报告,它们都来自同一个表,其中包含"本地商店"," ID"," TotalSpend", "会员卡号"。
Store Totalnumofmembers TotalSpendforall
----- ------------------ ---------------
Store A 1500 $100.50
Store B 2000 $500.00
Store C 400 $300.00
在尝试运行此查询时,它没有给我我想要的结果:
SELECT "Local Store",
(SELECT count(ID) FROM ListMembers WHERE Id=a.Id and "Member Card Number" is not null) AS totalnumofmembers,
(SELECT sum("total spend") FROM ListMembers WHERE Id=a.Id) AS totalspendforall FROM ListMembers a
GROUP BY "Local Store"
除了使用自联接之外还有其他方法吗? 谢谢
答案 0 :(得分:0)
如果您想在一个查询中执行此操作,则可以使用CASE
语句对在同一查询中使用有效卡号的成员进行条件计数,以总计总支出。
SELECT `Local Store`,
COUNT(CASE WHEN `Member Card Number` IS NOT NULL THEN 1 ELSE 0 END) AS totalnumofmembers,
SUM(`total spend`) AS totalspendforall
FROM ListMembers
GROUP BY `Local Store`
如果您不介意使用子查询,那么您可以尝试以下
SELECT t1.`Local Store`, t1.totalnumofmembers, t2.totalspendforall
FROM
(
SELECT `Local Store`, COUNT(*) AS totalnumofmembers
FROM ListMembers
WHERE `Member Card Number` IS NOT NULL
GROUP BY `Local Store`
) t1
INNER JOIN
(
SELECT `Local Store`, SUM(`total spend`) AS totalspendforall
FROM ListMembers
GROUP BY `Local Store`
) t2
ON t1.`Local Store` = t2.`Local Store`
答案 1 :(得分:0)
感谢名单。设法解决它。没有意识到SQL lite不像oracle那样使用to_date函数。都好。非常感谢你们。