嗨,这是我的疑问:
SELECT
CONCAT( YEAR( prm.fromdt ) , '|', MONTH( prm.fromdt ) ) AS k,
CONCAT( YEAR( prm.fromdt ) , ' - ', MONTH( prm.fromdt ) ) AS v,
FROM prm
GROUP BY k
ORDER BY `k` DESC
回归:
K V
2009|7 2009 - 7
2009|6 2009 - 6
NULL NULL
有没有办法NULL NULL
来获取我有多少空值。像
K V
2009|7 2009 - 7
2009|6 2009 - 6
Nulls 6
答案 0 :(得分:2)
添加COUNT()
SELECT
CONCAT( YEAR( prm.fromdt ) , '|', MONTH( prm.fromdt ) ) AS k,
CONCAT( YEAR( prm.fromdt ) , ' - ', MONTH( prm.fromdt ) ) AS v,
COUNT(*) AS c
FROM prm
GROUP BY k
ORDER BY `k` DESC
哪个应该返回
k v c
2009|7 2009 - 7 {count of this group}
2009|6 2009 - 6 {count of this group}
NULL NULL 6
答案 1 :(得分:2)
你可以这样做:
SELECT CONCAT( YEAR( prm.fromdt ) , '|', MONTH( prm.fromdt ) ) AS k,
coalesce(CONCAT( YEAR( prm.fromdt ) , ' - ', MONTH( prm.fromdt ) ), cast(count(*) as varchar(255)) AS v
FROM prm
GROUP BY k
ORDER BY `k` DESC
我不喜欢在一列中混合不同类型的数据。但是,这可能会满足您的需求。
答案 2 :(得分:1)
基于xdazz的回答:
select k, case when v is null then c else v end as v
from
(
SELECT
CONCAT( YEAR( prm.fromdt ) , '|', MONTH( prm.fromdt ) ) AS k,
CONCAT( YEAR( prm.fromdt ) , ' - ', MONTH( prm.fromdt ) ) AS v,
COUNT(*) AS c
FROM prm
GROUP BY k
) x
ORDER BY `k` DESC
但正如眩目指出的那样,你就是在混合列类型。您可以轻松地将计数转换为字符串值,但这并不能解决消费者隐含地在列v
中获取混合数据类型的事实。
答案 3 :(得分:0)
基本SQL是:
COUNT(somefield) WHERE prm.fromdt IS NULL
但如何实际使用这取决于你究竟在做什么。这听起来像你想要的与你在约会时做的不一样。如果你混合使用它们,它可能会很混乱。