假设我有两个表,如
Id date1. date2. status. code
1. .... ........ 1. AB110
2. ....... ..... 2. AB001
3. ....... ....... 1. AB120
4. ...... ........ 1. AB111
和table2
Code. Name. Display
AB110 Abc. Y
AB001 Xyx. Y
我想要这样的事情:
withdate. type1. type2. code. name
2 1. 1 AB110. Abc
1. 2. 3 AB001. Xyz
3. . 1. 2 AB120. Lol
1. 1 5 AB111. Zzz
Select code,
table2.name,
count(case when date1 is not null then id) as withdate,
count(case when status=1 then id) as type1,
count(case when status=2 then id) as type2
from table, table2
where table.code=table2.code
group by code, name
编写像这样的查询是否很严格?
答案 0 :(得分:0)
是的,编写类似的查询是正确的。逻辑很好,但在这种情况下有一个synthax错误。我希望您使用sum
聚合函数进行计数,如下所示。
select code,
table2.name,
sum(date1 is not null) as withdate,
sum(status=1) as type1,
sum(status=2) as type2
from table, table2
where table.code=table2.code
group by code, name;
这种方式当date1不为null时,将1添加到sum的cummated值中,否则添加零,就像计数一样。
答案 1 :(得分:0)
您的查询对我来说是正确的,除非您忘记完全限定列名并忘记end
表达式中的case
关键字。但是,您可以进行一些改进。
首先,你不应该使用隐式连接(在from
子句中有多个表) - 它们被认为已经被弃用了很多年,你应该使用join
子句。
其次,您没有提到您正在使用的版本,但Postgres 9.4引入了一个filter
子句,可以为您节省一些case
表达式的样板。
SELECT table1.code,
table2.name,
COUNT(*) FILTER (WHERE date1 IS NOT NULL) AS withdate,
COUNT(*) FILTER (WHERE status = 1) AS type1,
COUNT(*) FILTER (WHERE status = 2) AS type2
FROM table1
JOIN table2 ON table1.code = table2.code
GROUP BY table1.code, table2.name