Mssql 2个表的重复值?

时间:2015-01-27 22:31:11

标签: sql sql-server database select

我希望写入查询在结果下面做,但我的查询不起作用。


    Table A

    code    |    date
    -------------------------------------
    3            2015-01-26

    4            2015-01-27

    5            2015-01-27

    6            2015-01-26

    8            2015-01-26

Table B

code    |    Code B
-------------------------------------
3            12

3            10

5             3

6            10

6            12

8            12

Results

code B    |    value_Repetition 
-------------------------------------
12                   3

10                   2

3                     1

我的查询

DECLARE @ddd int

select @ddd = code FROM Table A where date between '2015-01-01' and '2015-01-27'

SELECT       code B ,COUNT(code B) AS value_Repetition 
    FROM     Table B
    where code = @ddd
    GROUP BY code B
    ORDER BY value_Repetition  DESC

2 个答案:

答案 0 :(得分:0)

您在计数功能中提到了列别名COUNT(code B)。 试试这个..

DECLARE @ddd int

select @ddd = code FROM Table A where date between '2015-01-01' and '2015-01-27'

SELECT       code B ,COUNT(code) AS value_Repetition 
    FROM     Table B
    where code = @ddd
    GROUP BY code
    ORDER BY value_Repetition  DESC

答案 1 :(得分:0)

这应该这样做。

CREATE TABLE TableA(
    Code    INT,
    [Date]  DATE
)
CREATE TABLE TableB(
    Code    INT,
    CodeB   INT
)
INSERT INTO TableA VALUES
(3, '2015-01-26'), (4, '2015-01-27'), (5, '2015-01-27'),
(6, '2015-01-26'), (8, '2015-01-26');
INSERT INTO TableB VALUES
(3, 12), (3, 10), (5, 3),
(6, 10), (6, 12), (8, 12);

SELECT
    b.CodeB,
    COUNT(b.CodeB) AS Value_Repetition
FROM TableA a
INNER JOIN TableB b
    ON a.Code = b.Code
WHERE
    a.[Date] BETWEEN '2015-01-01' AND '2015-01-27'
GROUP BY
    b.CodeB
ORDER BY
    COUNT(b.CodeB) DESC