这个查询有什么问题?他们每个人都分开工作,但是在我写完select *
后他们没有工作select * from
(SELECT COUNT(issuer_id) AS INSU_cnt, min_desc AS INSURANCE
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE (min_desc = 't')
GROUP BY min_desc)
UNION
(SELECT COUNT(issuer_id) AS Bank_cnt,min_desc AS BANKS
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE (min_desc = 'b')
GROUP BY min_desc
)
编辑: 我想问题是我在一个表中有所需的所有数据(带有查询),我想从该表中选择5行... 我有这张桌子:
Name Count
Bank 20
Insurance 10
Econ 10
我希望select语句是这样的: 选择bank_count,insurance_count,econ_count 我认为工会可以解决我的问题,但这没有多大意义......
答案 0 :(得分:2)
使用UNION
子句代替IN
,如下所示:
SELECT COUNT(issuer_id) AS Count, min_desc
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc IN('t', 'b')
GROUP BY min_desc
使用UNION
方法,你只会得到第一个查询命名的列,所以既然已经消失了,你可以在一个查询中做到这一点:)
对于您更新的问题:根据您使用的数据库而有所不同,但CASE
语句之类的内容可能会有效:
SELECT (CASE min_desc WHEN 't' THEN 'Insurance'
WHEN 'b' THEN 'Bank'
WHEN 'e' THEN 'Econ'
ELSE 'Other'
End) as Name, COUNT(issuer_id) AS Count
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc IN('t', 'b')
GROUP BY min_desc
或者,如果你有一个描述表,你可以加入它变得更干净/更易于维护......有几种方法可以解决这个问题,我不确定你的选择或平台是什么。
答案 1 :(得分:2)
我认为您发布的查询的具体问题是您需要括号:
SELECT * FROM (
(
SELECT COUNT(issuer_id) AS INSU_cnt, min_desc AS INSURANCE
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc = 't'
GROUP BY min_desc
)
UNION
(
SELECT COUNT(issuer_id) AS Bank_cnt, min_desc AS BANKS
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc = 'b'
GROUP BY min_desc
)
) T1
然而,这个查询实际上并不是你想要做的。你真正想做的是:
SELECT
(
SELECT COUNT(issuer_id)
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc = 't'
) AS ins_cnt,
SELECT COUNT(issuer_id)
FROM issuer INNER JOIN code ON economy_sect = cod_id
WHERE min_desc = 'b'
) AS bank_cnt
答案 2 :(得分:0)
使用UNION,您将两个结果集附加到单个表中。大多数SQL实现都希望每个UNIONed集合中的列具有相同的名称。在您的情况下,将INSU_cnt和BANK_cnt的名称更改为通用(可能是“cnt”)和INSURANCE和BANKS的名称也是通用的。
或者,还有UNION CORRESPONDING,它通过为它们创建单独的列来处理不同的列名,但我认为这不是你想要的。
如果这没有帮助,可能会发布您从日志中收到的错误。
答案 3 :(得分:0)
这应该是
select count(issuer_id) as cnt, min_desc
from issue inner join code on economy_sect = cod_id
where min_desc in ('t', 'b')
group by min_desc