首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >复杂的SQL查询

复杂的SQL查询
EN

Stack Overflow用户
提问于 2009-09-21 11:51:11
回答 2查看 180关注 0票数 1

我有下面的db表(为了说明这个问题而简化了)。

CampaignTx

代码语言:javascript
复制
campaignTx_id | member_id | date_created | shop_id
1 | 2 | 7/12/2009 | 2
2 | 4 | 7/13/2009 | 3
3 | 6 | 7/14/2009 | 4
4 | 5 | 8/14/2009 | 3
5 | 10| 8/19/2009 | 1

可靠性

代码语言:javascript
复制
Reliability_id | campaignTx_id | status
1 | 3 | 0
2 | 2 | 1
3 | 4 | 2
4 | 5 | 3
5 | 7 | 1

商店

代码语言:javascript
复制
Shop_id | Shop_name | City_id
1 | shop 1| 5
2 | shop 2| 7
3 | shop 3| 7
4 | shop 4| 6

城市

代码语言:javascript
复制
City_id | City_name
5 | city 1
6 | city 2
7 | city 3

我想要的是下表(每行按城市、年份和月份分组):

代码语言:javascript
复制
City| year | month| num_of_campaignTx_records | num_of_reliability_records | num_of reliability_records with status = 0 |num_of reliability_records with status = 1| num_of reliability_records with status = 2| num_of reliability_records with status = 3

我应该如何编写SQL查询来获取这个表?

我现在有以下查询,但我不知道如何写最后4列:

代码语言:javascript
复制
select datepart(year,[Tx].date_created) as year,
datepart(month,[Tx].date_created) as month,
[city].nameTc as city,
count([Tx].date_created) as 'total num of campaign Tx records', 
count([rel].CreateDate) as 'num of reliability records'

from campaigntx as [Tx]

full join [Reliability] as [rel]
on [rel].[CampaignTx_id] = [Tx].[CampaignTx_id]

join shop as [shop]
on [Tx].shop_id = [shop].shop_id

join City as [city]
on [city].city_id = [shop].city_id

group by datepart(year,[Tx].date_created),datepart(month,[Tx].date_created), [city].nameTc
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-09-21 12:05:48

我还没有测试过它,但是下面几行中的内容应该可以工作

代码语言:javascript
复制
sum(when [rel].status = 1 then 1 else 0) as 'num of reliability records'
票数 0
EN

Stack Overflow用户

发布于 2009-09-21 12:11:36

看起来像是PIVOT的案例

代码语言:javascript
复制
WITH Qry AS (
select datepart(year,[Tx].date_created) as year,
datepart(month,[Tx].date_created) as month,
[city].nameTc as city,
count([Tx].date_created) as 'total num of campaign Tx records', 
count([rel].CreateDate) as 'num of reliability records',
[re].status
from campaigntx as [Tx]

full join [Reliability] as [rel]
on [rel].[CampaignTx_id] = [Tx].[CampaignTx_id]

join shop as [shop]
on [Tx].shop_id = [shop].shop_id

join City as [city]
on [city].city_id = [shop].city_id

group by datepart(year,[Tx].date_created),datepart(month,[Tx].date_created), [city].nameTc
)
SELECT year, month, city, [toal num of campaign Tx records], 
  [0] as [No status 0], [1] as [No status 1], [2] as [No status 2], ...
 FROM Qry
PIVOT ( SUM([number or reliability records]) FOR status in ([0],[1],[2],...) ) AS PVT;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1454143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档