如何在一个表上的Sql Join在列中包含相同的值

时间:2014-04-02 05:02:19

标签: sql sql-server-2008 join

P_Id    Catid   Score   ArtId   PostId  PhaseId UserId  Deleted ModDate
26      1       20      57      5       18      8       0       2014-03-29
27      2       18      57      5       18      8       0       2014-03-29
28      3       7       57      5       18      8       0       2014-03-29
29      4       5       57      5       18      8       0       2014-03-29
30      5       20      57      5       18      8       0       2014-03-29
31      1       12      57      1       18      9       0       2014-03-29
32      2       15      57      1       18      9       0       2014-03-29
33      3       15      57      1       18      9       0       2014-03-29
34      4       15      57      1       18      9       0       2014-03-29
35      5       19      57      1       18      9       0       2014-03-29

我想要这样的结果......

Catid            Judge1       Judge2  
1                   20          12
2                   18          15
3                    7          15
4                    5          15
5                   20          19    

2 个答案:

答案 0 :(得分:5)

您不需要任何联接来执行此操作,可以使用CASE语句和聚合函数来完成。

SQL Fiddle

MS SQL Server 2012架构设置

CREATE TABLE Table1
    ([P_Id] int, [Catid] int, [Score] int, [ArtId] int, [PostId] int, [PhaseId] int, [UserId] int, [Deleted] int, [ModDate] varchar(10))
;

INSERT INTO Table1
    ([P_Id], [Catid], [Score], [ArtId], [PostId], [PhaseId], [UserId], [Deleted], [ModDate])
VALUES
    (26, 1, 20, 57, 5, 18, 8, 0, '2014-03-29'),
    (27, 2, 18, 57, 5, 18, 8, 0, '2014-03-29'),
    (28, 3, 7, 57, 5, 18, 8, 0, '2014-03-29'),
    (29, 4, 5, 57, 5, 18, 8, 0, '2014-03-29'),
    (30, 5, 20, 57, 5, 18, 8, 0, '2014-03-29'),
    (31, 1, 12, 57, 1, 18, 9, 0, '2014-03-29'),
    (32, 2, 15, 57, 1, 18, 9, 0, '2014-03-29'),
    (33, 3, 15, 57, 1, 18, 9, 0, '2014-03-29'),
    (34, 4, 15, 57, 1, 18, 9, 0, '2014-03-29'),
    (35, 5, 19, 57, 1, 18, 9, 0, '2014-03-29')
;

查询1

SELECT
  Catid,
  SUM(CASE WHEN userid = 8 THEN score ELSE 0 END) AS Judge1,
  SUM(CASE WHEN userid = 9 THEN score ELSE 0 END) AS Judge2
FROM table1
GROUP BY catid

<强> Results

| CATID | JUDGE1 | JUDGE2 |
|-------|--------|--------|
|     1 |     20 |     12 |
|     2 |     18 |     15 |
|     3 |      7 |     15 |
|     4 |      5 |     15 |
|     5 |     20 |     19 |

答案 1 :(得分:0)

select a.catid,a.score,b.score from
(select * from Table1 where userid = 8) a inner join 
(select * from Table1 where userid = 9) b on a.Catid = b.Catid