I have a table like this, named Tour Details
.
| dealdate | Tours | Weeknumber | Country | SubVenue |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 2022-01-12 | 3 | 49 | India | SP1 |
| 2022-11-25 | 4 | 48 | India | SP2 |
| 2022-10-14 | 5 | 42 | India | SP3 |
| 2023-01-05 | 3 | 2 | India | SP1 |
| 2023-01-05 | 4 | 2 | India | SP2 |
| 2023-01-06 | 5 | 2 | US | SP1 |
| 2023-02-24 | 3 | 9 | US | SP2 |
| 2022-02-12 | 4 | 7 | US | SP3 |
| 2023-02-19 | 5 | 8 | US | SP1 |
| 2023-02-27 | 6 | 10 | US | SP2 |
I need to create a table. This table should have information like
Grp | Total Tours |
---|---|
Tours SP1 | 16 |
Tours SP2 | 17 |
Tours SP3 | 19 |
I have tried :
WITH CTE AS (
SELECT 'Tours ' +SubVenue AS Grp
FROM Tour_Details
)
SELECT CTE.Grp
, SUM(T.Tours) AS Total
FROM Tour_Details T
LEFT JOIN CTE ON CTE.Grp = T.SubVenue
GROUP BY CTE.Grp, T.SubVenue
But the output I get is:
Grp | Total Tours |
---|---|
NULL | 16 |
NULL | 17 |
NULL | 19 |
Any help would be greatly appreciated
4条答案
按热度按时间dpiehjr41#
This can be done using a simple aggregation query :
cfh9epnr2#
When you do this
SELECT 'Tours ' + SubVenue AS Grp FROM Tour_Details
yourGrp
equalsTours SP1
and you try to join it toSubVenue
which equalsSP1
.Tours SP1
<>SP1
. You need to have the equals values in columns which you use in join.And you can do it simpler.
6yjfywim3#
I think you're over-thinking your problem, you just need a simple aggregation:
jhkqcmku4#
I think your SQL is failing because you are concatenating the string 'Tour ' with the contents of the subvenue field then using that concatenated value from the query result to LEFT JOIN back to the Tour Details table field subvenue. The join is returning the cartesian product (if it's still called that, sorry, I'm old...) along with the sum results.
I created a table using VARCHAR(100) for all the string fields and INTEGER for all the number fields. I'm not sure what RDBMS you're using but my dev database is postgres so the syntax is slightly different (namely, the string concatenation operator is '||' rather than '+' but I think the SQL you're looking for is along the lines of:
I created a view with it like this:
And a table like this:
Both work fine and I'm sure the syntax would be similar enough in your database.