加入同一张表
Posted
技术标签:
【中文标题】加入同一张表【英文标题】:JOIN the same table 【发布时间】:2013-02-20 12:56:50 【问题描述】:您好,我有表格徽章,其中包含 facility
和 date
列(其他列不重要)。
我想select count(*)
应该是这样的:
DATE | FACILITY 4 COUNT | FACILITY 1 COUNT
12/12/2012 | 234 | 647
我为facility
1 和 4 编写了两个单独的查询,但是如何将它加入一个查询;
SELECT
date,
COUNT(*)
FROM badge
WHERE facility = 3
AND xtype = 19
AND date BETWEEN 'some_date' AND 'some_date'
GROUP BY date
另一个查询的不同之处仅在于设施的值。
编辑:它是informix 数据库。
【问题讨论】:
【参考方案1】:SELECT date,
SUM(case when facility = 1 then 1 else 0 end) "FACILITY 1 COUNT",
SUM(case when facility = 4 then 1 else 0 end) "FACILITY 4 COUNT"
FROM badge
WHERE (facility = 1 OR facility = 4)
AND xtype = 19
AND date BETWEEN 'some_date' AND 'some_date'
GROUP BY date
【讨论】:
我会在 where 子句中添加 AND (facility = 1 OR facility = 4) 以提高查询效率。【参考方案2】:试试看,
SELECT date,
SUM(CASE WHEN facility = 3 THEN 1 ELSE 0 END) `Facility 3 Count`,
SUM(CASE WHEN facility = 1 THEN 1 ELSE 0 END) `Facility 1 Count`
FROM badge
WHERE xtype = 19 AND
date BETWEEN 'some_date' AND 'some_date'
GROUP BY date
【讨论】:
以上是关于加入同一张表的主要内容,如果未能解决你的问题,请参考以下文章