[英]How do I change the query to just show one row SQL?
我正在嘗試編譯每個月發生多少實例的視圖。 我有下面的代碼,它得到了我的答案,但也給出了多行。 如何將視圖限制為一行,每列是每個月的實例數量?
CREATE VIEW new_users_per_month AS
SELECT (
SELECT COUNT(id) AS January
FROM master_table
WHERE month(created_at)=1) AS January,
(
SELECT COUNT(id) AS February
FROM master_table
WHERE month(created_at)=2) AS February,
(
SELECT COUNT(id) AS March
FROM master_table
WHERE month(created_at)=3) AS March
FROM master_table;
未正確測試,我將創建虛擬對象並稍后進行測試,但支持我的評論
select *
from
(
select
t.id,
month(t.created_at) as MTH_CRE
from master_table as t
) as q
pivot
(
count(id) for MTH_CRE in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) as pvt
做條件聚合:
select count(case when month(created_at) = 1 then id end) as Jan,
count(case when month(created_at) = 2 then id end) as Feb,
count(case when month(created_at) = 3 then id end) as Mar
from master_table t;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.