计算几年中同一周的相等列数

时间:2014-11-10 16:10:30

标签: sql sql-server

我有一个表,其中包含1个名为Week的列和5个名为n1,n2,n3,n4和n5的列。 我想计算每周有多少n1,n2 ... n5列匹配。

到目前为止,我创建了一个查询,显示按周排序的所有n1 ... n5

select e.Week, e.Year, e.n1, e.n2, e.n3, e.n4, e.n5, e.Date
from Entries e
order by e.Week asc, e.Year asc

CREATE TABLE [dbo].[Enties](
    [Id] [int] IDENTITY(1,1) NOT NULL,  
    [Week] [int] NULL,
    [n1] [int] NULL,
    [n2] [int] NULL,
    [n3] [int] NULL,
    [n4] [int] NULL,
    [n5] [int] NULL,
    [sup] [int] NULL
 CONSTRAINT [PK_Enties] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

我使用的是SQL Server,但这是一个常见的SQL问题。 任何想法我怎样才能做到这一点?

更新: 假设该表包含3年,每年3个相等的星期。 我想知道有多少

week1.n1=week2.n1=week3.n1, week1.n2=week2.n2=week3.n2, ... 

每周都相等。

结果将类似于

Week1 = 0 match,
Week2 = 2 match,
Week3 = 1 matches,
...

1 个答案:

答案 0 :(得分:1)

在SQL Server中,如果在CASE表达式中包装,则可以使用布尔表达式作为其数值。

您可以计算同时匹配的数量:

select
    (Round/2) as Week
,   e.Year
,   SUM(
        (case when n1=n2 then 1 else 0 end)
    +   (case when n1=n3 then 1 else 0 end)
    +   (case when n1=n4 then 1 else 0 end)
    +   (case when n1=n5 then 1 else 0 end)
    +   (case when n2=n3 then 1 else 0 end)
    +   (case when n2=n4 then 1 else 0 end)
    +   (case when n2=n5 then 1 else 0 end)
    +   (case when n3=n4 then 1 else 0 end)
    +   (case when n3=n5 then 1 else 0 end)
    +   (case when n4=n5 then 1 else 0 end)
    ) as MatchCount
from Entries
group by (Round/2), Year
order by Round asc, Year asc

SUM的参数列出了表中所有{n i ,n j }的对,计算成对匹配的数量。