Сложный SQL-запрос - PullRequest
       5

Сложный SQL-запрос

1 голос
/ 21 сентября 2009

У меня есть следующие таблицы БД (которые упрощены для иллюстрации проблемы)

CampaignTx

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

Надежность

Reliability_id | campaignTx_id | status
1 | 3 | 0
2 | 2 | 1
3 | 4 | 2
4 | 5 | 3
5 | 7 | 1

Магазин

Shop_id | Shop_name | City_id
1 | shop 1| 5
2 | shop 2| 7
3 | shop 3| 7
4 | shop 4| 6

Город

City_id | City_name
5 | city 1
6 | city 2
7 | city 3

Мне нужна следующая таблица (каждая строка сгруппирована по городу, году и месяцу):

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 столбца:

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

Ответы [ 2 ]

0 голосов
/ 21 сентября 2009

выглядит как чехол для PIVOT

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 голосов
/ 21 сентября 2009

Я не проверял, но что-то в следующих строках должно работать

sum(when [rel].status = 1 then 1 else 0) as 'num of reliability records'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...