Posts

Showing posts with the label pivot

Dynamic SQL query to return results in columns

Image
Dynamic SQL query to return results in columns I have this basic database table and am SQL beginner. +-------------+--------+----------+ | location | Week | Expenses | +-------------+--------+----------+ | Backoffice | 201851 | 80 | | frontoffice | 201852 | 110 | | Backoffice | 201901 | 120 | | Backoffice | 201902 | 70 | | frontoffice | 201903 | 68 | +-------------+--------+----------+ Is there a way to dynamically retrieve the last 5 weeks result, instead of hard coding it every time in my pivot table? Here is my code: SELECT * from (SELECT[week] ,[Expenses] from [cafe].[dbo].[table]where location = 'Backoffice' ) as Total_Expenses pivot (sum([expenses]) for [week] in ([201902],[201903],[201904],[201905],[201906],[201907],[201908],[201909])) as pivotable; I would like to be able to just enter "5" and it shows me the last 5 week. May be by a "max" formula" what RDBMS system? SQ...

Flatten Json Output

Flatten Json Output How can I turn this data into a flat data frame? I've tried using json_normalize and pivot, but I can't seem to get the format right. This is my desired out put format: SiteName|SiteId|...|CompressorMeterRefID|TankID|TankNumber...|TankID|TankNumber...|TankID|... DateandTime|... Please advise [{'SiteName': 'Reinschmiedt 1-4H (CRP 11)', 'SiteId': 57, 'SiteRefId': 'OK10020', 'Choke': '', 'GasMeter1': 53.25, 'GasMeter1Name': 'Check Meter', 'GasMeter1RefId': '', 'GasMeter2Name': '', 'GasMeter2RefId': '', 'GasMeter3Name': '', 'GasMeter3RefId': '', 'OilMeter1Name': '', 'OilMeter1RefId': '', 'OilMeter2Name': '', 'OilMeter2RefId': '', 'WaterMeter1': 0.0, 'WaterMeter1Name': 'Water Meter', ...