我的表格就像这个VB(名字字符(25),金额数字(6),ret_date日期):
Name Amount Ret_date ---- ------ -------- abc 500 2011-01-21 def 200 2011-01-20 ghi 1000 xyz 800 2011-01-22 def 200 def 400 2011-02-01 pqr 2100 2011-02-12 abc 3000 abc 4100 xyz 700 2011-01-22
我想要的是(根据不同名称的ret_date计算:总计数,返回计数,待处理计数):
Name tc rc pc
abc 3 1 2
def 3 2 1
xyz 2 2 0
ghi 1 0 1
pqr 1 1 0
我尝试了以下查询,没有任何效果!
SELECT vb.name, COUNT(*) tc, r.rc, p.pc FROM vb, ;
(SELECT name, COUNT(*) rc FROM vb WHERE ret_date != {} group BY name) r, ;
(SELECT name, COUNT(*) pc FROM vb WHERE ret_date = {} group BY name) p ;
GROUP BY vb.name ORDER BY tc desc
SELECT vb.name, COUNT(*) tc, r.rc, p.pc FROM vb ;
LEFT JOIN (select name, COUNT(*) rc FROM vb WHERE ret_date != {} group BY name) r ON r.name = vb.name ;
LEFT JOIN (select name, COUNT(*) pc FROM vb WHERE ret_date = {} group BY name) p ON p.name = vb.name ;
GROUP BY vb.name
SELECT vb.name, COUNT(*) tc, r.rc, p.pc FROM vb ;
LEFT JOIN (select r.name, COUNT(*) rc FROM vb r WHERE ret_date != {} group BY name) r ON r.name = vb.name ;
LEFT JOIN (select p.name, COUNT(*) pc FROM vb p WHERE ret_date = {} group BY name) p ON p.name = vb.name ;
GROUP BY vb.name
我能够通过3个单独的查询(总计数,ret_date = {}的计数,ret_date!= {})获得计数,但无法使用单个查询同时获取。请帮我获得所需的输出。我是SQL的新手,可以理解基础知识,但是像连接,子查询这样的东西仍然很难理解!如果您能解释一下您的查询的作用,将会很有帮助。
注意:我正在使用MS Visual Foxpro 9.0(Windows 7)。 {} 是用于表示Foxpro中日期类型空虚的符号,!= 不等于运算符。
非常感谢。
答案 0 :(得分:3)
SELECT name, COUNT(DISTINCT name) as uc, COUNT(*) as tc, SUM(IF(ret_date IS NULL, 0, 1)) as rc, SUM(IF(ret_date IS NOT NULL, 0, 1)) as pc
FROM vb
GROUP BY name;
我无法访问Foxpro,但这适用于MySQL。希望你能调整它以适合你的目的。
答案 1 :(得分:0)
我没有使用Foxpro的经验,但我认为COUNT(*)
将给出您的总计数,COUNT(Ret_Date)
将为您提供待处理的计数(因为它不会计算空值)。然后COUNT(*) - COUNT(Ret_Date)
(tc - rc)将提供您的待处理计数。这可以消除对子查询的需要(如果VFP在计数时表现得像其他DBMS一样)。
SELECT Name, COUNT(*) tc, COUNT(Ret_Name) rc, COUNT(*) - COUNT(Ret_Name) pc
FROM VB
GROUP BY Name;