I have a large table with this structure:
myTable: otherTable:
+----------+------+-------+ +-----+-------+-----+
| Date | Type | Ref | | ID | Field | Ref |
+----------+------+-------+ +-----+-------+-----+
| 1/1/2020 | 1 | XXX | | 1 | Val1 | XXX |
| 1/1/2020 | 2 | XXX | | 2 | Val2 | YYY |
| 1/2/2020 | 1 | YYY | | 3 | Val3 | AAA |
| ... | ... | ... | | ... | val4 | BBB |
+----------+------+-------+ +-----+-------+-----+
I'd like to count all the rows with a certain Type, in a specific Date interval with a single Ref value.
Result:
+-----+-------+-----+-------+
| ID | Field | Ref | Count |
+-----+-------+-----+-------+
| 1 | Val1 | XXX | 3 |
| 2 | Val2 | YYY | 1 |
| 3 | Val3 | AAA | 0 |
| ... | val4 | BBB | 2 |
+-----+-------+-----+-------+
Is this the best way to count values after the date filter?
SELECT otherTable.* ,
( SELECT Count(*)
FROM myTable
WHERE myTable.Type IN ( 2, 12 )
AND myTable.Ref = otherTable.Ref
AND Date BETWEEN Dateadd('d', now(), -7) AND Dateadd('d', now(), +7)
) as myCount
FROM otherTable
Or maybe this?
SELECT otherTable.* ,
( SELECT Count(*)
FROM ( SELECT * FROM myTable
WHERE myTable.Type IN ( 2, 12 )
AND myTable.Ref = otherTable.Ref
AND Date BETWEEN Dateadd('d', now(), -7) AND Dateadd('d', now(), +7)
)
) as myCount
FROM otherTable
I'm learning SQL and looking for way to save performances. Thank you in advance!