我坚持建立一个复杂的查询,并希望有人可以帮助我,如果它可能的话。我有一个表“竞争对手”,这里有一些列:
Type | Brand | Model | Date | Resolution | etc.
该表格将有重复的Model
条目(明显相同Brand
,但可能有不同的Type
(两种可能的类型:'ProAV'和'Disti'))。我需要构建一个输出如下表的查询:
Top (ProAV) | Top (Disti) | Last Occurrence | Brand | Model | Resolution | etc.
基本上我需要一个能够获得不同类型,品牌和型号的查询,但要计算找到多少重复项并将该数字放入Top(ProAV)或Top( Disti),以Type
为准。我需要从重复项中提取最近的(给定日期),以便我可以将其日期作为Last Occurrence
字段。我希望这是有道理的,如果没有,请告诉我。非常感谢!
答案 0 :(得分:2)
SELECT SUM(CASE WHEN Type = 'ProAV' THEN 1 ELSE 0 END) AS TopProAV,
SUM(CASE WHEN Type = 'Disti' THEN 1 ELSE 0 END) AS TopDisti,
MAX(Date) AS LastOccurence,
Brand, Model, Resolution
FROM Competitor
GROUP BY Brand, Model, Resolution
编辑:根据评论,您可以使用子查询或CTE来完成您想要的操作。类似的东西:
WITH cteMaxDate AS (
SELECT SUM(CASE WHEN Type = 'ProAV' THEN 1 ELSE 0 END) AS TopProAV,
SUM(CASE WHEN Type = 'Disti' THEN 1 ELSE 0 END) AS TopDisti,
MAX(Date) AS LastOccurence,
Brand, Model, Resolution
FROM Competitor
GROUP BY Brand, Model, Resolution
)
SELECT md.TopProAV, md.TopDisti,
md.LastOccurentce,
md.Brand, md.Model, md.Resolution,
c.AdditionalColumn1, c.AdditionalColumn2
FROM cteMaxDate md
INNER JOIN Competitor c
ON md.Brand = c.Brand
AND md.Model = c.Model
AND md.Resolution = c.Resolution
AND md.LastOccurence = c.Date
答案 1 :(得分:1)
您的Type
数量有限吗?在这种情况下,您可以使用pivot解决您的问题
更具体地说,对于表
Type Model
---- -----
A X
B X
C Y
A Z
NULL NULL
您运行此查询
Select Model, [A], [B], [C]
From
(select Model, Type
from dbo.Competitor) as SourceTable
PIVOT
(Count([Type]) for [Type] in ([A], [B], [C])) as PivotTable
获取
Model A B C
------ - - -
X 1 1 0
Y 0 0 1
Z 1 0 0