Skip to content

Tag: sql

Sql to fetch records only if related other table records exist

Table: user id compId 1 comp1 2 comp1 Table: Company id name comp1 coke comp2 pepsi need a MYSQL query which should fetch company record only if it has one or more users, when passed a company id. I will have other where conditions on company table. Can this be achieved by joins? example 1: query(comp1) resul…

SQL group and condition sum in the last row

I have several items which belongs to different group, some are unknown group. I need the sum of each group by date. I just try below SQL but still not exactly what I want: DB: SAP HANA Data: Item PG NET_VALUE_USD EMANAGER_DATE 1 1 100 2021-09 2 1 200 2021-10 3 2 300 2021-09 4 2 400 2021-09 5 3

SQL query to find the second occurrence of an element in a database

For example I have this table: I want to get the row where the PersonID occurs for the second time. So the desired output needs to be (for one of the person ID) : What would be the query for this scenario? Answer Use ROW_NUMBER() Function For this scenario Please Refer this link for how to use this function d…

counting consecutive months in sas

From the sample data below, I’m trying to count how many consecutive months a member has. In the event if an ID has a gap month in the middle, the output should show the most recent count of consecutive months this member had, see example below. dataset=one ID Month 72 01SEP2020 72 01OCT2020 72 01NOV202…

Zero lead digit for a number removed when concatenating in SQL

I have written a couple of PL SQL Functions to return a currency and amount from a compressed field. These work perfectly individually. e.g. returns GBP returns 0.1 Concatenating the 2… returns GBP.1 I want it to be GBP0.1, any idea what is going wrong? The amount function returns a NUMBER the currency …