问题
I had a similar issue which was kindly resolved for me by Gordon Linoff Solution by the use of row_number() and conditional aggregation but I don't believe this will work in this instance?
I have a hypothetical database for a stamp collection as the image below, were each stamp be can be saved under any of the three conditions in the Status Table and any of the three conditions under the MintUsedTable. Therefore a total of 9 possible States. These are both Lookup Tables and there Id's are stored in the QuantatiesTable which links back to the StampTable via the StampQuantatiesTable.
I can retrieve the StampTable information per stamp, I can then use the id to get the stamp states (a combination of status and MintUsed). See results table.
This is not ideal but works for say just one stamp which requires two calls to the database and one call to the C# switch statement, but if I want to do this for multiple stamps it results in multiple calls to the database and multiple calls to a C# switch statement and is therefore very slow and in efficient.
Is there a better way to achieve this and if so any assistance would be much appreciated?
Ultimately I would like to be able to combine the principles of this solution with the row_number() and conditional aggregation solution referred to above so that I can retrieve all the stamp data.
Thanks for the assistance
回答1:
If the grid is what you really want to have then you need to group them and check for each and you even don't need to do any modification in c# for it either if I'm not mistaken:
SELECT s.StampId
, s.Country
, s.Year
, MAX(case when q.statusId = 1 and q.MintUsedId = 1 then 1 ELSE 0 END) as HaveMNH
, MAX(case when q.statusId = 1 and q.MintUsedId = 2 then 1 ELSE 0 END) as HaveMH
, ....
FROM Stamp s
LEFT JOIN StamQuantities sq
ON s.StampId = sq.StampId
LEFT JOIN Quantities q
ON q.quantitiesId = qs.quantitiesId
GROUP BY s.StampId
, s.Country
, s.Year
来源:https://stackoverflow.com/questions/65147268/one-to-many-query-and-row-number-and-conditional-aggregation