Click here to Skip to main content
16,020,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
I have two tables
Table 1 looks like this

|ID	| Repeats|
-----------
|A|	1
|A| 1
|A|	0
|B|	2
|B|	2
|C|	2
|D|	1

Table 2 looks like this
|ID	|values|
-----------
|A	|100|
|B	|200|
|C	|100|
|D	|300|

Using a view I need a result like this
|ID	|values	|Repeats|
-------------------
|A	|100|	NA|
|B	|200|	2|
|C	|100|	2|
|D	|300|	1[enter image description here][1]

that means, I want unique ID, its values and Repeats. Repeats value should display NA when there are multiple values against single ID and it should display the Repeats value in case there is single value for repeats.

Initially I needed to display the max value of repeats so I tried the following view

ALTER VIEW [dbo].[BookingView1]
AS
SELECT bv.*, bd2.Repeats FROM Table1 bv 
JOIN
(
    SELECT distinct bd.id, bd.Repeats FROM table2 bd
    JOIN
    (
      SELECT Id, MAX(Repeats) AS MaxRepeatCount
      FROM table2
      GROUP BY Id
    ) bd1
    ON bd.Id = bd1.Id
    AND bd.Repeats = bd1.MaxRepeatCount
) bd2
ON bv.Id = bd2.Id;

and this returns the correct result but when trying to implement the CASE it fails to return unique ID results. Please help!!

The following link shows the tables.

  [1]: http://i.stack.imgur.com/xN8CP.jpg


What I have tried:

ALTER VIEW [dbo].[BookingView1]
AS
SELECT bv.*, bd2.Repeats FROM Table1 bv
JOIN
(
SELECT distinct bd.id, bd.Repeats FROM table2 bd
JOIN
(
SELECT Id, MAX(Repeats) AS MaxRepeatCount
FROM table2
GROUP BY Id
) bd1
ON bd.Id = bd1.Id
AND bd.Repeats = bd1.MaxRepeatCount
) bd2
ON bv.Id = bd2.Id;

and this returns the correct result but when trying to implement the CASE it fails to return unique ID results. Please help!!
Posted
Updated 21-Apr-16 8:26am

1 solution

Based on the sample data, something like this should work:
SQL
WITH cteRepeats As
(
    SELECT
        ID,
        Min(Repeats) As MinRepeats,
        Max(Repeats) As MaxRepeats
    FROM
        Table1
    GROUP BY
        ID
)
SELECT
    T2.ID,
    T2.Values,
    CASE
        WHEN T1.MinRepeats = T1.MaxRepeats THEN CAST(T1.MinRepeats As varchar(10))
        ELSE 'NA'
    END As Repeats
FROM
    Table2 As T2
    LEFT JOIN cteRepeats As T1
    ON T1.ID = T2.ID
;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900