SQL How do I select plans not associated with any country - sql-server

Please check http://sqlfiddle.com/#!18/1acd1/2
I'm passing UserId to get User's countryid so I can fetch plans according to user's country.
I have plans specific to countries but I don't have plans for all countries so when I pass userid where I don't have any plan for that user/country at the moment no rows returns but in that case I need to show default plans (plans with country id = '1') to that user.
Please see fiddle, In case of userid='4' no rows returns so in that case I need to show default plans to that user. all default plans have countryid=1
I hope you understand my question :) thanks

Here is my take on it.
I took a different approach and started from the tblProfile because your input for this query is actually a UserId so I found it more logical to follow this process:
For the UserId, fetch PlanId of his CountryId
If User's CountryId does not exist in lstCountry or has no PlanId replace User's CountryId by the default CountryId=1 (as mentioned in the comments below)
Finally, fetch Plan details and Currency for the final CountryId
Tables definitions
CREATE TABLE lstCountry(
CountryID int,
CountryTitle varchar(100),
CurrencyCode varchar(3))
INSERT INTO lstCountry (CountryId, CountryTitle, CurrencyCode) VALUES
(1, 'USA', 'USD'),
(2, 'GB', 'GBP'),
(3, 'France', 'EUR')
CREATE TABLE tblProfile(
UserId int,
CountryId int)
INSERT INTO tblProfile (UserId, CountryId) VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 4)
CREATE TABLE tblPlan (
PlanId int,
PlanTitle nvarchar(50),
PlanPrice money,
CountryId int)
INSERT INTO tblPlan (PlanId, PlanTitle, PlanPrice, CountryId) VALUES
(1, 'PlanDefault', 10, 1),
(2, 'Plan2', 20, 2),
(3, 'Plan3', 30, 3),
(4, 'PlanDefault', 40, 1),
(5, 'Plan5', 50, 2)
Query
select distinct f.PlanId,
f.PlanTitle,
f.PlanPrice,
e.CurrencyCode
from (
select case when c.PlanId is null then '1' else a.CountryId end as CountryId
from tblProfile a
left join lstCountry b on a.CountryId=b.CountryId
left join tblPlan c on b.CountryId=c.CountryId
where UserId=4
) d
inner join lstCountry e on d.CountryId=e.CountryId
inner join tblPlan f on d.CountryId=f.CountryId
Result for UserId=1:
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-------------|-----------|--------------|
| 1 | PlanDefault | 10 | USD |
| 4 | PlanDefault | 40 | USD |
Result for UserId=2
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-----------|-----------|--------------|
| 2 | Plan2 | 20 | GBP |
| 5 | Plan5 | 50 | GBP |
Result for UserId=3
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-----------|-----------|--------------|
| 3 | Plan3 | 30 | EUR |
Result for UserId=4
| PlanId | PlanTitle | PlanPrice | CurrencyCode |
|--------|-------------|-----------|--------------|
| 1 | PlanDefault | 10 | USD |
| 4 | PlanDefault | 40 | USD |
Here is the SQL Fiddle
http://sqlfiddle.com/#!18/7068c/8/0

I think a LEFT JOIN and second parse of the table might achieve this. If not, then please look at #JuanCarlosOropeza comments and update your post with Sample and expected data.
SELECT p.PlanId,
p.PlanTitle,
p.PlanPrice,
ISNULL(c.CurrencyCode, d.CurrencyCode) AS CurrencyCode
FROM tblPlan p
LEFT JOIN lstCountry c ON c.CountryId = p.CountryId
LEFT JOIN lstCountry d ON c.CountryId IS NULL
AND d.CountryId = 226
WHERE P.CountryId = (SELECT sq.CountryId
FROM tblProfile sq --Not sure if this requires a Default Country
WHERE UserId = #UserId)
AND p.IsVisible = '1';

Related

How to generate XML path within CASE

Edit: Trying to query a XML Path list that has been narrowed down by a case statement. Column 'displayname' contains over 700 unique values throughout the database. However, based on other criteria including the AccountID and if RenderedValue is = '', the remaining results will most likely be less than 5. The variables in my query is I cannot explicitly declare an Account Id or DisplayName.
I have a successful CASE statement on it's own. But trying to also have the XML PATH statement pulls all the data from the table and comma separates it instead of just the results from the previous CASE statement. Can't figure out how to nest them together. Besides the GUID in column 1, values are nvarchar.
Query w/o CASE
select tb1.AccountID,
tb3.DisplayName,
tb4.RenderedValue
from Accounts tb1
join Display tb2 on tb2.AccountID = tb1.AccountID
inner join ExtractDetail tb3 on tb3.ExtractID = tb2.ExtractID
left join ExtractDetailData tb4 on tb4.ExtractDetailID = tb3.ExtractDetailID
result:
+-----------+---------------+-----------------------+
| AccountID | DisplayName | RenderedValue |
+-----------+---------------+-----------------------+
| E8175 | FirstName | John |
| E8175 | LastName | Smith |
| E8175 | StreetAddress | 123 Washington Street |
| E8175 | City | |
| E8175 | State | NY |
| E8175 | ZipCode | |
| E8175 | PhoneNumber | 555-555-5555 |
| E8175 | Email | JohnSmith#aol.com |
+-----------+---------------+-----------------------+
Query w/ CASE
select tb1.AccountID,
CASE When tb4.RenderedValue = ''
Then tb3.DisplayName
Else ''
End As MissingField
from Accounts tb1
join Display tb2 on tb2.AccountID = tb1.AccountID
inner join ExtractDetail tb3 on tb3.ExtractID = tb2.ExtractID
left join ExtractDetailData tb4 on tb4.ExtractDetailID = tb3.ExtractDetailID
Where tb4.RenderedValue =''
Result:
+-----------+--------------+
| AccountID | MissingField |
+-----------+--------------+
| E8175 | City |
| E8175 | ZipCode |
+-----------+--------------+
Expected Output:
+-----------+--------------+
| AccountID | MissingField |
+-----------+--------------+
| E8175 | City,ZipCode |
+-----------+--------------+
i think this code will help you
create table #temp (AccountID varchar(20),DisplayName varchar(20),RenderedValue varchar(255))
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','FirstName','John')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','LastName','Smith')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','StreetAddress','123 Washington Street')
insert into #temp (AccountID,DisplayName,RenderedValue) values ('E8175','City','')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','State','NY')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','ZipCode','')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','PhoneNumber','555-555-5555 ')
insert into #temp (AccountID,DisplayName,RenderedValue) values
('E8175','Email','JohnSmith#aol.com')
SELECT distinct
P.AccountID,
STUFF
(
(
SELECT ',' + case when RenderedValue = '' Then DisplayName Else '' End
FROM #temp M
FOR XML PATH(''), type
).value('.', 'varchar(max)'), 1, 1, ''
) AS Temp
FROM
#temp P
Drop table #temp

Sum column for stock calculation

I'm trying to calculate stock in sql. I've 3 table product, purchase and sales.
product table is
+----+------------------+
| id | product_name |
+----+------------------+
| 1 | apple |
|----|------------------|
| 2 |banana |
|----|------------------|
| 3 |mango |
+----+------------------+
Now color table
+----+------------------+
| id | color_name |
+----+------------------+
| 1 | dark |
|----|------------------|
| 2 | light |
+----|------------------+
purchase table is
+-------+-------------+
| id | quantity |color
+-------+-------------+
| 1 | 15 |dark
+-------+-------------+
| 1 | 10 |light
+-------+-------------+
| 2 | 5 |dark
+-------+-------------+
| 3 | 25 |light
+-------+-------------+
and sales table is
+-------+-------------+
| id | quantity |color
+-------+-------------+
| 1 | 5 |dark
+-------+-------------+
| 1 | 5 |light
+-------+-------------+
| 2 | 5 |dark
+-------+-------------+
| 3 | 5 |light
+-------+-------------+
Purchase and sales table have foreign key id references id of product table. Now I'm trying to calculate stock available i.e. difference of purchase and sales in below format on the basis of color too
+----+------------------+-------------+
| id | product_name | quantity |color
+----+------------------+-------------+
| 1 | apple | 10 |dark
|----|------------------|-------------|
| 1 | apple | 5 |light
|----|------------------|-------------|
| 2 |banana | 0 |dark
|----|------------------|-------------|
| 3 |mango | 20 |light
+----+------------------+-------------+
You may looking for this
SELECT p.id,p.Name,Purchase.purchaseQty-sales.salseQty as totalQty
FROM Product p
OUTER APPLY(
SELECT purchase.id, SUM(purchase.quantity) purchaseQty
FROM purchase
where purchase.id= p.id
GROUP BY purchase.id
)Purchase
OUTER APPLY(
SELECT sales.id, SUM(sales.quantity) salseQty
FROM sales
where sales.id= p.id
GROUP BY sales.id
)sales
SELECT a.id, a.product_name,
SUM(b.quantity) - SUM(c.quantity) as 'quantity'
FROM product a
LEFT JOIN purchase b
ON a.id=b.id
LEFT JOIN sales c
ON b.id = c.id group by a.id, a.product_name
(I didn't test anything)
Try this solution with outer apply.
drop table if exists dbo.tProduct;
drop table if exists dbo.tPurchase;
drop table if exists dbo.tSale;
create table dbo.tProduct (
id int
, product_name varchar(100)
);
create table dbo.tPurchase (
id int
, quantity int
);
create table dbo.tSale (
id int
, quantity int
);
insert into dbo.tProduct (id, product_name)
values (1, 'apple'), (2, 'banana'), (3, 'mango');
insert into dbo.tPurchase (id, quantity)
values (1, 15), (2, 10), (1, 5), (3, 25);
insert into dbo.tSale (id, quantity)
values (1, 5), (3, 10), (1, 5), (3, 5), (2, 5);
select
p.id
, p.product_name
, pur.Quantity - sal.Quantity as Quantity
from dbo.tProduct p
outer apply (
select
sum(tp.quantity) as Quantity
from dbo.tPurchase tp
where p.id = tp.id
) pur
outer apply (
select
sum(tp.quantity) as Quantity
from dbo.tSale tp
where p.id = tp.id
) sal

Update postgres table to squash duplicate values in second table

I have a postgresql schema with two tables:
tableA: tableB:
| id | username | | fk_id | resource |
| 1 | user1 | | 2 | item1 |
| 2 | user1 | | 1 | item3 |
| 3 | user1 | | 1 | item2 |
| 4 | user2 | | 4 | item5 |
| 5 | user2 | | 5 | item8 |
| 6 | user3 | | 3 | item9 |
The foreign key fk_id in tableB references id in tableA.
How can I update all of the foreign key id's of tableB to point to the lowest entry for a unique username in tableA?
update table_b b
set fk_id = d.id
from table_a a
join (
select distinct on (username) username, id
from table_a
order by 1, 2
) d using(username)
where a.id = b.fk_id;
Test it here.
The query used inside the update gives actual_id, username, desired_id:
select a.id actual_id, username, d.id desired_id
from table_a a
join (
select distinct on (username) username, id
from table_a
order by 1, 2
) d using(username)
actual_id | username | desired_id
-----------+----------+------------
1 | user1 | 1
2 | user1 | 1
3 | user1 | 1
4 | user2 | 4
5 | user2 | 4
6 | user3 | 6
(6 rows)
We define your tables:
CREATE TABLE tableA (id, username) AS
SELECT * FROM
(
VALUES
(1, 'user1'),
(2, 'user1'),
(3, 'user1'),
(4, 'user2'),
(5, 'user2'),
(6, 'user2')
) AS x ;
CREATE TABLE tableB (fk_id, resource) AS
SELECT * FROM
(
VALUES
(2, 'item1'),
(1, 'item3'),
(1, 'item2'),
(4, 'item5'),
(5, 'item8'),
(3, 'item9')
) AS x ;
With that info, you can create a (virtual) conversion table, and use it to update your data:
-- Using tableA, make a new table with the
-- minimum id for every username
WITH username_to_min_id AS
(
SELECT
min(id) AS min_id, username
FROM
tableA
GROUP BY
username
)
-- Convert the previous table to a id -> min_id
-- conversion table
, id_to_min_id AS
(
SELECT
id, min_id
FROM
tableA
JOIN username_to_min_id USING(username)
)
-- Use this conversion table to update tableB
UPDATE
tableB
SET
fk_id = min_id
FROM
id_to_min_id
WHERE
-- JOIN condition with table to update
id_to_min_id.id = tableB.fk_id
-- Take out the ones that won't change
AND (fk_id <> min_id)
RETURNING
* ;
The result you would get is:
+-------+----------+----+--------+
| fk_id | resource | id | min_id |
+-------+----------+----+--------+
| 1 | item1 | 2 | 1 |
| 1 | item9 | 3 | 1 |
| 4 | item8 | 5 | 4 |
+-------+----------+----+--------+
Shows you that three rows have been updated, that had fk_id = (2, 3, 5), and have now (1, 1, 4). (The id is the "old" fk_id value).
You can check it at http://rextester.com/EQPH47434
You can "squeeze everything" [change every virtual table name by its definition, and do a couple of SELECT optimizations] and get this equivalent query (probably less clear, yet totally equivalent):
UPDATE
tableB
SET
fk_id = min_id
FROM
tableA
JOIN
(
SELECT
min(id) AS min_id, username
FROM
tableA
GROUP BY
username
) AS username_to_min_id
USING (username)
WHERE
tableA.id = tableB.fk_id
AND (fk_id <> min_id)
RETURNING
* ;

SQL statement - join based on date

I need to write a statement joining two tables based on dates.
Table 1 contains time recording entries.
+----+-----------+--------+---------------+
| ID | Date | UserID | DESC |
+----+-----------+--------+---------------+
| 1 | 1.10.2010 | 5 | did some work |
| 2 | 1.10.2011 | 5 | did more work |
| 3 | 1.10.2012 | 4 | me too |
| 4 | 1.11.2012 | 4 | me too |
+----+-----------+--------+---------------+
Table 2 contains the position of each user in the company. The ValidFrom date is the date at which the user has been or will be promoted.
+----+-----------+--------+------------+
| ID | ValidFrom | UserID | Pos |
+----+-----------+--------+------------+
| 1 | 1.10.2009 | 5 | PM |
| 2 | 1.5.2010 | 5 | Senior PM |
| 3 | 1.10.2010 | 4 | Consultant |
+----+-----------+--------+------------+
I need a query which outputs table one with one added column which is the position of the user at the time the entry has been made. (the Date column)
All date fileds are of type date.
I hope someone can help. I tried a lot but don't get it working.
Try this using a subselect in the where clause:
SQL Fiddle
MS SQL Server 2008 Schema Setup:
CREATE TABLE TimeRecord
(
ID INT,
[Date] Date,
UserID INT,
Description VARCHAR(50)
)
INSERT INTO TimeRecord
VALUES (1,'2010-01-10',5,'did some work'),
(2, '2011-01-10',5,'did more work'),
(3, '2012-01-10', 4, 'me too'),
(4, '2012-11-01',4,'me too')
CREATE TABLE UserPosition
(
ID Int,
ValidFrom Date,
UserId INT,
Pos VARCHAR(50)
)
INSERT INTO UserPosition
VALUES (1, '2009-01-10', 5, 'PM'),
(2, '2010-05-01', 5, 'Senior PM'),
(3, '2010-01-10', 4, 'Consultant ')
Query 1:
SELECT TR.ID,
TR.[Date],
TR.UserId,
TR.Description,
UP.Pos
FROM TimeRecord TR
INNER JOIN UserPosition UP
ON UP.UserId = TR.UserId
WHERE UP.ValidFrom = (SELECT MAX(ValidFrom)
FROM UserPosition UP2
WHERE UP2.UserId = UP.UserID AND
UP2.ValidFrom <= TR.[Date])
Results:
| ID | Date | UserId | Description | Pos |
|----|------------|--------|---------------|-------------|
| 1 | 2010-01-10 | 5 | did some work | PM |
| 2 | 2011-01-10 | 5 | did more work | Senior PM |
| 3 | 2012-01-10 | 4 | me too | Consultant |
| 4 | 2012-11-01 | 4 | me too | Consultant |
You can do it using OUTER APPLY:
SELECT ID, [Date], UserID, [DESC], x.Pos
FROM table1 AS t1
OUTER APPLY (
SELECT TOP 1 Pos
FROM table2 AS t2
WHERE t2.UserID = t1.UserID AND t2.ValidFrom <= t1.[Date]
ORDER BY t2.ValidFrom DESC) AS x(Pos)
For every row of table1 OUTER APPLY operation fetches all table2 rows of the same user that have a ValidFrom date that is older or the same as [Date]. These rows are sorted in descending order and the most recent of these is finally returned.
Note: If no match is found by the OUTER APPLY sub-query then a NULL value is returned, meaning that no valid position exists in table2 for the corresponding record in table1.
Demo here
This works by using a rank function and subquery. I tested it with some sample data.
select sub.ID,sub.Date,sub.UserID,sub.Description,sub.Position
from(
select rank() over(partition by t1.userID order by t2.validfrom desc)
as 'rank', t1.ID as'ID',t1.Date as'Date',t1.UserID as'UserID',t1.Descr
as'Description',t2.pos as'Position', t2.validfrom as 'validfrom'
from temployee t1 inner join jobs t2 on -- replace join tables with your own table names
t1.UserID=t2.UserID
) as sub
where rank=1
This query would work
select t1.*,t2.pos from Table1 t1 left outer join Table2 t2 on
t1.Date=t2.Date and t1.UserID=t2.UserID

Date-based multiple group by T-SQL query

First of all, execuse the longer question, but I will try to put it as simply as possible...
I'm trying to write a kind of a reporting query, but I'm having a problem getting the desired results. The problem:
Employee table
Id | Name
---------------
1 | John Smith
2 | Alan Jones
3 | James Jones
Task table
Id | Title | StartDate | EmployeeId | Estimate (integer - ticks)
----------------------------------------------------------------------------
1 | task1 | 21.08.2011 | 1 | 90000000000
2 | task2 | 21.08.2011 | 1 | 150000000
3 | task3 | 22.08.2011 | 2 | 1230000000
Question:
How to get the estimate summary per day, grouped, but to include all the employees?
Like this:
Date | EmployeeId | EmployeeName | SummaryEstimate
-------------------------------------------------------------
19.08.2011 | 1 | John Smith | NULL
19.08.2011 | 2 | Alan Jones | NULL
19.08.2011 | 3 | James Jones | NULL
20.08.2011 | 1 | John Smith | NULL
20.08.2011 | 2 | Alan Jones | NULL
20.08.2011 | 3 | James Jones | NULL
21.08.2011 | 1 | John Smith | 90150000000
21.08.2011 | 2 | Alan Jones | NULL
21.08.2011 | 3 | James Jones | NULL
22.08.2011 | 1 | John Smith | NULL
22.08.2011 | 2 | Alan Jones | 1230000000
22.08.2011 | 3 | James Jones | NULL
What I currently do is I have a "dates" table with 30years of days. I left join and group by that table to get other dates included too. Well, here is the query:
SELECT dates.value, employee.Id, employee.Name, sum(task.Estimate)
FROM TableOfDates as dates
left join Tasks as task on (dates.value = convert(varchar(10), task.StartTime, 101))
left join Employees as employee on (employee.Id = task.EmployeeId)
WHERE dates.value >= '2011-08-19' and dates.value < '2011-08-22'
GROUP BY dates.value, employee.Id, employee.Name
ORDER BY dates.value, employee.Id
The convert call is to get the date part of the DateTime column.
The result that I get is:
Date | EmployeeId | EmployeeName | SummaryEstimate
-------------------------------------------------------------
19.08.2011 | NULL | NULL | NULL
20.08.2011 | NULL | NULL | NULL
21.08.2011 | 1 | John Smith | 90150000000
22.08.2011 | 2 | Alan Jones | 1230000000
I am there half of the way, I get dates that are not in the two base joined tables (Employees and Tasks) but I cannot also have all the employees included as in the table shown before this one.
I've tried cross-joining, then subqueries, but little luck there. Any help would be very much appreciated ! Thank you for having the time to go through all of this, I hope I was clear enough...
SELECT DE.DateValue, DE.EmployeeId, DE.EmployeeName, sum(task.Estimate)
FROM
( SELECT
D.value AS DateValue
, E.Id AS EmployeeId
, E.Name AS EmployeeName
FROM
TableOfDates D
CROSS JOIN Employees E ) DE
left join Tasks as task on DE.DateValue = convert(varchar(10), task.StartTime, 101)
AND DE.EmployeeId = task.EmployeeId
WHERE DE.DateValue >= '2011-08-19' and DE.DateValue < '2011-08-22'
GROUP BY DE.DateValue, DE.EmployeeId, DE.EmployeeName
ORDER BY DE.DateValue, DE.EmployeeId
Note that this solution offers the possibility to drop the day-table as you may use a dynamic recursive CTE instead.
The other CTE:s (Employees and Tasks) can be substituted with the real tables.
DECLARE #startDate DATETIME = '2011-08-01'
DECLARE #endDate DATETIME = '2011-09-01'
;WITH Employees(Id,Name)
AS
(
SELECT 1, 'John Smith'
UNION ALL
SELECT 2, 'Alan Jones'
UNION ALL
SELECT 3, 'James Jones'
)
,Tasks (Id, Title, StartDate, EmployeeId, Estimate)
AS
(
SELECT 1, 'task1', '2011-08-21', 1, 90000000000
UNION ALL
SELECT 2, 'task2', '2011-08-21', 1, 150000000
UNION ALL
SELECT 3, 'task3', '2011-08-22', 2, 1230000000
)
,TableOfDates(value)
AS
(
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, #startDate), 0)
UNION ALL
SELECT DATEADD(DAY, 1, value)
FROM TableOfDates
WHERE value < #endDate
)
SELECT dates.value
,employee.Id
,employee.Name
,SUM(task.Estimate) AS SummaryEstimate
FROM TableOfDates dates
CROSS JOIN Employees employee
LEFT JOIN Tasks task
ON dates.value = task.StartDate
AND (employee.Id = task.EmployeeId)
WHERE dates.value >= '2011-08-19'
AND dates.value < '2011-08-26'
GROUP BY
dates.value
,employee.Id
,employee.Name
ORDER BY
dates.value
,employee.Id
use this query:
create table #T_dates (id_date int identity(1,1),inp_date datetime)
create table #T_tasks (id_task int identity(1,1),key_date int, key_emp int, est int)
create table #T_emp (id_emp int identity(1,1),name varchar(50))
insert #T_dates (inp_date) values ('08.19.2011')
insert #T_dates (inp_date) values ('08.20.2011')
insert #T_dates (inp_date) values ('08.21.2011')
insert #T_dates (inp_date) values ('08.22.2011')
insert #T_dates (inp_date) values ('08.23.2011')
insert #T_dates (inp_date) values ('08.24.2011')
--select * from #T_dates
insert #T_emp (name) values ('John Smith')
insert #T_emp (name) values ('Alan Jones')
insert #T_emp (name) values ('James Jones')
--select * from #T_emp
insert #T_tasks (key_date,key_emp,est) values (4,1,900000)
insert #T_tasks (key_date,key_emp,est) values (4,1,15000)
insert #T_tasks (key_date,key_emp,est) values (5,2,123000)
--select * from #T_tasks
select inp_date,id_emp,name,EST
from #T_emp
cross join #T_dates
left join
(
select key_date,key_emp,SUM(est) 'EST' from #T_tasks group by key_date,key_emp
) Gr
ON Gr.key_emp = id_emp and Gr.key_date = id_date
where inp_date >= '2011-08-19' and inp_date <= '2011-08-22'
order by inp_date,id_emp

Resources