Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
每个月和每年使用一行id的sql分组_Sql_Sql Server - Fatal编程技术网

每个月和每年使用一行id的sql分组

每个月和每年使用一行id的sql分组,sql,sql-server,Sql,Sql Server,我有一张桌子,上面有月份、年份和这样的id +-------+-----------+----- | month | year | id +-------+-----------+----- | 1 | 2016 |1 +-------+-----------+----- | 2 | 2016 |2 +-------+-----------+----- | 2 | 2016 |3 +-------+-----------+----

我有一张桌子,上面有月份、年份和这样的id

+-------+-----------+-----
| month |    year   |  id
+-------+-----------+-----
| 1     |  2016     |1
+-------+-----------+-----
| 2     | 2016      |2
+-------+-----------+-----
| 2     | 2016      |3
+-------+-----------+-----
我想要一个sql查询,每个月/年只给我一行,如果是单行,则id为空;如果该月/年有多行,则id为空

在上述情况下

+-------+-----------+-----
| month |    year   |  id
+-------+-----------+-----
| 1     |  2016     |1
+-------+-----------+-----
| 2     | 2016      |null
+-------+-----------+-----

如何使用sql server 2012执行此查询?

您可以使用聚合和案例执行此操作:

select month, year,
       (case when min(id) = max(id) then min(id) end) as id
from t
group by month, year;

注意:
month
year
是列的错误名称,因为它们是保留字。如果这些确实是列的名称,则需要对其进行转义。

**问题:*如果为单行,则每个月/年只有一行id,如果该月/年有多行,则id为null

with cte
    as
    (
    select row_number() over (partition by month,year  order by (Select 1)) as rn,
    month,year,id
    from
    table
    )
    select 
    case when rn>1 then null else id end as 'id',
    month,
    year
    from
    cte

我错过了OP中关于NULL的部分,这里是一个调整后的查询

DECLARE @tbl TABLE
(
    Month INT NOT NULL,
    Year INT NOT NULL,
    Id INT NOT NULL
)

INSERT INTO @tbl VALUES
   (2016, 1, 1)
   ,(2016, 2, 2)
   ,(2016, 2, 3)

SELECT 
    Month
   ,Year
   ,CASE WHEN COUNT(Id) > 1 THEN NULL ELSE COUNT(Id) END AS [Id]
FROM @tbl
GROUP BY Month, Year

做一个
分组,统计每个月和每年的行数。有一个
case
表达式,如果有一行,则使用min(id)返回,否则(超过1行)返回null

select month, year, case when count(*) = 1 then min(id) else null end
from tablename
group by month, year;

我认为,如果有多个值,则用户希望为空值…如果id为单,则每月/年只有一行,如果该月/年有多行,则id为空。如果在一年/月内发现两次相同的id,则将返回该id。据我所知,在这种情况下应为空。@jarlh。有趣。我将该问题解释为行中有一个“单一值”的id。这个问题是不明确的。你能添加两个相等的行,都是(3,2016,4),并调整预期结果吗?jarlh,我想要的正确结果与Gordon Linodd的答案一致,谢谢