SQL Server - selecting a specific ID from a table - sql-server

I will explain what I have done so far and ask my question at the end.
First I created my external & internal variables (note that #EDelivery is a table type that included the columns FoodID and Quantity):
#EDelivery DeliveryTblType readonly
Declare #NumberOfMinutes smallint, #FoodWeight int, #WeightCapacity int,
#DroneID int, #TimeOfWeek varchar
I then read this in, giving me the total weight of all items ordered and read in the weight capacity from the DronesTbl:
select #FoodWeight = SUM(FoodWeight * Quantity)
from #EDelivery as del
inner join Foods on del.FoodID = Foods.FoodID
select #WeightCapacity = Drones.WeightCapacity
from dbo.Drones
My question is how do I select a specific drone to compare its weightcapacity to the food total weight

You need to set the variable #WeightCapacity according to the #droneid value. Right now, you are setting this variable to last drone in your drones table.
If you change your second query to what's below then it should work.
select #WeightCapacity =
Drones.WeightCapacity
from dbo.Drones
where DroneID =#droneID

Related

How to query values when a column has N value

So I have the following table:
And I'm trying to write a Query where I can send the code BR_BN as a variable in my WHERE clause
and if I get BR_BN then I want to retrieve the records with this code AND the records with the Code_FS RB02. On the other side when I get the value AB_CP, I want to include the recordes with the Code_FS RB01.
Here's the Query I've tried so far:
DECLARE #Code_OB VARCHAR(20) = 'BR_BN'
SELECT * FROM Dummy_AV
WHERE FK = 2
OR
(#Code_OB = 'BR_BN' AND Code_FS = 'RB02' AND Code_FS = #Code_OB)
But it doesn't work, it retrieves all the records regardless of the FK, and/or the #Code_FS.
How can I achieve this?
Thanks for the help.
You don't note the FK = 2 being needed, yet you have it in front of an OR in the WHERE clause. I think this is what you're after, if it isn't exactly what you're aiming for hopefully it gets you on the right track. For future questions, always helpful to paste your sample data as data instead of an image.
DECLARE #Code_OB VARCHAR(20) = 'BR_BN'
SELECT * FROM Dummy_AV
WHERE FK = 2 -- you will get all rows where this is true
OR
((#Code_OB = Code_OB AND Code_FS = 'RB02') OR (Code_OB = 'AB_CP' AND Code_FS = 'RB01')) -- you will get all rows where one of these is true

Sqlite3 calculate the percentages from totals

Question(*):
The total number of cases and deaths as a percentage of the population, for each country (with country, % cases of population, % deaths of population as columns)
I have two tables :
countriesAffected(countriesAndTerritories,geoId,countryterritoryCode,popData2019,continentExp)
victimsCases(dateRep,cases,deaths,geoId)
where primary key(geoid)
I tried to do (*) by this method:
SELECT countriesAndTerritories, (100 *SUM(victimsCases.cases) / popData2019)as "cases" ,(100 * SUM(deaths) / popData2019) as "deaths"
FROM countriesAffected
INNER JOIN victimsCases ON victimsCases.geoId = countriesAffected.geoId
GROUP BY countriesAndTerritories
ORDER BY countriesAndTerritories DESC;
Error: near line 2: near "SELECT countriesAndTerritories": syntax error
But for some reason I get all types of syntax errors, i tried to sort it out but with no results. And not sure where did i went wrong.
If you are getting the error Error: near line 2: near "SELECT countriesAndTerritories": syntax error then the issue is with LINE 1 (perhaps no ; at the end of line 1).
Otherwise your query works albiet probably not as intended (as you may well want decimal places for the percentages).
Consider the following (that shows your SQL with additional SQL added to work as intended (see casesV2 and deathsV2 that utilise CAST to force INTEGER to REAL)).
DROP TABLE If EXISTS victimsCases;
DROP TABLE IF EXISTS countriesAffected;
CREATE TABLE IF NOT EXISTS countriesAffected (countriesAndTerritories TEXT,geoId INTEGER PRIMARY KEY,countryterritoryCode TEXT,popData2019 INTEGER,continentExp TEXT);
CREATE TABLE IF NOT EXISTS victimsCases (dateRep TEXT,cases INTEGER ,deaths INTEGER,geoId INTEGER);
INSERT INTO countriesAffected VALUES
('X',1,'XXX',10000,'?'),('Y',2,'YYY',20000,'?'),('Z',3,'ZZZ',30000,'?')
;
INSERT INTO victimsCases VALUES
('2019-01-01',100,20,1),('2019-01-02',100,25,1),('2019-01-03',100,15,1),
('2019-01-01',30,5,2),('2019-01-02',33,2,2),
('2019-01-01',45,17,3),('2019-01-02',61,4,3),('2019-01-03',75,7,3)
;
SELECT countriesAndTerritories,
(100 *SUM(victimsCases.cases) / popData2019)as "cases", /* ORIGINAL */
(100 * SUM(deaths) / popData2019) as "deaths", /* ORIGINAL */
CAST(SUM(victimsCases.cases) AS FLOAT) / popData2019 * 100 AS "casesV2",
CAST(SUM(victimscases.deaths) AS FLOAT) / popData2019 * 100 as "deathsV2"
FROM countriesAffected
INNER JOIN victimsCases ON victimsCases.geoId = countriesAffected.geoId
GROUP BY countriesAndTerritories
ORDER BY countriesAndTerritories DESC;
DROP TABLE If EXISTS victimsCases;
DROP TABLE IF EXISTS countriesAffected;
The result of the above is :-

Updating one table's column in SQL Server from another

I have a table of measurements from weather stations, with station names (in Hebrew):
I also have created a table of those weather stations with their latitudes and longitudes:
I've written a query that should update the first table with the lat/longs from the second, but it's not working:
update t1
set t1.MeasurementLat = t2.Latitude,
t1.MeasurementLong = t2.Longitude
from [dbo].[Measurements] as t1
inner join [dbo].[StationCoords] as t2 on t1.StationName like t2.Station
I think there is a problem with the way the station name is being read, and perhaps something to do with encoding, because this query brings back an empty result, too:
SELECT TOP (5) *
FROM [dbo].[Measurements]
WHERE [StationName] = 'אריאל מכללה';
Any ideas?
Your example names are not the same. Perhaps this will work:
update m
set MeasurementLat = sc.Latitude,
MeasurementLong = sc.Longitude
from dbo.[Measurements] m join
dbo.[StationCoords] sc
on m.StationName like sc.Station + '%';

Totalling up values across salesforce account hierarchies

I'm struggling to find an approach to the following problem, can anyone suggest a high level approach.
Using talend, I have an input set of values for a set of accounts (from CSV):
AccountId, ValueXYZ__c
I want to store ValueXYZ against the SFDC account, which is no problem, but then I want to totalise ValueXYZ up for all the accounts with the same parent to
Account.Parent.TotalValueXYZ
I then want to "roll" this all the way up the accounts hierarchy:
Imagine account hierarchy:
A
-B
--C
--D
-E
--F
--G
I want 3 values on A:
ValueXYZ = account A's ValueXYZ
TotalValueXYZ = total of ValueXYZ values for all accounts under A in the hierarchy
TOTAL = formula field to add together the previous 2 values
I want 3 values on account B
ValueXYZ = account B's ValueXYZ
TotalValueXYZ = total of ValueXYZ values for accounts C & D
TOTAL = formula field to add together the previous 2 values
I want 3 values on account C
ValueXYZ = account C's ValueXYZ
TotalValueXYZ = 0
TOTAL = formula field to add together the previous 2 values
I've tried several approaches, but can't get any of them to work!
Where is the hierarchy information stored? If you can flatten the hierarchy information in a key-value pair format, then it is straightforward. Just read your input file and do a lookup/join on the hierarchy file. You will have to loop through until you get to the base record
The crux of my problem was in not knowing each accounts position in a hierarchy. Once I had that in place, I could loop from the lowest level to the highest level, totalling these values up to their parents.
Here is the T-SQL I wrote to mark each account with it's Hierarchy Position (HILEVEL)
TRUNCATE TABLE [TALEND_WORKSPACE].[dbo].[SFDCAccount]
INSERT INTO [TALEND_WORKSPACE].[dbo].[SFDCAccount] (Id, ParentId, QCIYTDOneTime, QCIYTDRecurring, HILEVEL)
SELECT Id, ParentId, ValueXYZ, '0'
FROM [TALEND_WORKSPACE].[dbo].[SFDCAccountRawData]
WHERE ParentId = ' ';
USE TALEND_WORKSPACE
IF OBJECT_ID('dbo.sfdcaccounthierarchy', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sfdcaccounthierarchy];
GO
CREATE PROCEDURE [dbo].[sfdcaccounthierarchy]
AS
DECLARE #v_counter int;
DECLARE #v_lastccounter int;
DECLARE #v_max int;
SET #v_counter = 0;
SET #v_lastccounter = 0;
SET #v_max = 10;
WHILE (#v_counter < #v_max)
BEGIN
SET #v_lastccounter = #v_counter;
SET #v_counter = #v_counter+1;
PRINT #v_counter;
INSERT INTO [dbo].[SFDCAccount] (Id, ParentId, QCIYTDOneTime, QCIYTDRecurring, HILEVEL)
SELECT Id, ParentId, ValueXYZ, #v_counter
FROM [TALEND_WORKSPACE].[dbo].[SFDCAccountRawData]
WHERE ParentId IN (SELECT Id FROM [TALEND_WORKSPACE].[dbo].[SFDCAccount]
WHERE HILEVEL = #v_lastccounter);
if ##ROWCOUNT != 0
BREAK;
END
GO
EXEC [TALEND_WORKSPACE].[dbo].[sfdcaccounthierarchy];

Only the last entry is selected to itab

At my selection Screen you can choose with a radio button Group with which kind of number you want to select the information. (material number, construction contract or customer order).
After choosing a kind, the User have to fill in the number(s) into the corresponding select option.
With this information I select the information I need an move them to the itab t_marc. This table has the same fields as marc.
When the User choose material number at the selection screen everything works fine and the values to every number the user wrote down is displayed at the ALV-List.
When selecting by one of the other numbers, the values in output are also right, but only the information to the last denoted number will be edited.
How can I move all numbers to my itabs?
PARAMETERS: p_mat RADIOBUTTON GROUP radi.
PARAMETERS: p_auf RADIOBUTTON GROUP radi.
PARAMETERS: p_vbl RADIOBUTTON GROUP radi.
SELECT-OPTIONS: s_matnr FOR marc-matnr.
SELECT-OPTIONS: s_aufnr FOR aufk-aufnr.
SELECT-OPTIONS: s_vbeln FOR vbap-vbeln.
start-of-selection
IF p_mat = 'X'.
SELECT * FROM marc
INTO TABLE t_marc
WHERE matnr IN s_matnr
AND werks = p_werks.
ELSEIF p_auf = 'X'.
SELECT * FROM afpo
INTO TABLE t_afpo
WHERE aufnr IN s_aufnr.
LOOP AT t_afpo.
SELECT * FROM marc
INTO TABLE t_marc
WHERE matnr = t_afpo-matnr
AND werks = p_werks.
ENDLOOP.
ELSEIF p_vbl = 'X'.
SELECT * FROM vbap
INTO TABLE t_vbap
WHERE vbeln = s_vbeln-low
AND posnr IN s_posnr.
LOOP AT t_vbap.
SELECT * FROM marc
INTO TABLE t_marc
WHERE matnr = t_vbap-matnr
AND werks = p_werks.
ENDLOOP.
You're overwriting the records every time in this loop (and the similar loops).
LOOP AT t_afpo.
SELECT * FROM marc
INTO TABLE t_marc
WHERE matnr = t_afpo-matnr
AND werks = p_werks.
ENDLOOP.
"INTO TABLE" overwrites every time. You could switch to "APPENDING TABLE." Alternatively, I would use a for all entries select instead (no loop).
SELECT * FROM marc
INTO TABLE t_marc
FOR ALL ENTRIES IN t_afpo
WHERE matnr = t_afpo-matnr
AND werks = p_werks.
Always make sure there are records in the driver table (in this case, t_afpo) or you will have performance issues.

Resources