协助MSSQL查询分组数据

时间:2013-02-18 18:58:03

标签: sql-server

示例数据已更新 - 我在确认之前发布了数据

使用 SQL Server ,我返回了以下数据:

select id, dateofservice, first, second, third, fourth, fn, ln
from servicesTbl

示例数据:

id  dateofservice   first   second  third   fourth  fn      ln      
-------------------------------------------------------------------
1   2/01/2013       Y       N       N       Y       John    Doe    
2   2/01/2013       N       N       Y       Y       Sue     Fisher    
2   2/01/2013       Y       N       N       N       Sue     Fisher    
3   2/01/2013       Y       N       N       Y       Daivd   Smith    
3   2/01/2013       N       N       Y       N       Daivd   Smith       
4   2/01/2013       N       N       N       N       Bob     Denver    

我需要知道如何编写我的查询,以便Sue Fisher和David Smith的记录都在一行上,这意味着输出应该是这样的:

1   2/01/2013       Y       N       N       Y       John    Doe    
2   2/01/2013       Y       N       Y       Y       Sue     Fisher    
3   2/01/2013       Y       N       Y       Y       Daivd   Smith       
4   2/01/2013       N       N       N       N       Bob     Denver    

此查询对我不起作用,我不知道如何以我想要的格式获取输出。

select id, dateofservice, first, second, third, fourth, fn, ln    
from servicesTbl    
group by ln

示例数据已更新 - 我在确认之前发布了数据

3 个答案:

答案 0 :(得分:1)

SELECT 
    id, 
    dateofservice, 
    (CASE WHEN SUM(first) > 0 THEN 1 ELSE 0 END) AS first, 
    (CASE WHEN SUM(second) > 0 THEN 1 ELSE 0 END) AS second, 
    (CASE WHEN SUM(third) > 0 THEN 1 ELSE 0 END) AS third, 
    (CASE WHEN SUM(fourth) > 0 THEN 1 ELSE 0 END) AS fourth, 
    fn, 
    ln 
    OVER (PARTITION BY id)
FROM servicesTbl

这可能也会起作用,考虑它并且它更简洁:

SELECT 
    id, 
    dateofservice, 
    MAX(first) AS first, 
    MAX(second) AS second, 
    MAX(third) AS third, 
    MAX(fourth) AS fourth, 
    fn, 
    ln 
    OVER (PARTITION BY id)
FROM servicesTbl

在像MySQL这样的事情中,通常的做法是:

SELECT 
    id, 
    dateofservice, 
    MAX(first) AS first, 
    MAX(second) AS second,
    MAX(third) AS third,
    MAX(fourth) AS fourth,
    fn, 
    ln
FROM servicesTbl
GROUP BY id

...但我认为我说MSSQL会抱怨fn,而不是聚合函数或不在GROUP BY子句中是正确的:使用上面的OVER PARTITION方法应该解决这个问题。

请注意,这是未经测试的,因为我没有手持MSSQL,但应该指向正确的方向。

答案 1 :(得分:0)

select id,CONVERT(VARCHAR(10),Dateofservice,111) as Dateofservice,
 MAX(first) as first ,
 MAX(second) as second,
 MAX(third) as third,
 MAX(fourth) as fourth, fn, ln from dbo.ttest
group by id,CONVERT(VARCHAR(10),Dateofservice,111),fn, ln

我已将该表命名为tttest,您可以使用您的表名。另外,我使用随机日期格式更改它以适合自己。

答案 2 :(得分:0)

使用CF,我能够通过然后执行查询

<table>
    <cfoutput query='rsData' group="id">
        <cfoutput>
            <tr>
                <td>#dateformat(dateofservice,'mm/dd/yyyy')#</td>
                <td>#first#</td>
                <td>#second#</td>
                <td>#third#</td>
                <td>#fourth#</td>
                <td>#fn#</td>
                <td>#ln#</td>
            </tr>
        </cfoutput>
    </cfoutput>
</table>