mssql 2个表的重复值?

Mssql The repetition value of the 2 tables?

我想编写查询来执行以下结果,但我的查询不起作用。


    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

您在计数函数中提到了列别名 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

这应该可以做到。

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