Dynamic columns when pivoting - sql

I have a table of equipment, a table of customers and a sparse table of equipment and customers. I want to produce a query that returns a 1 if the equipment/Customer table record exists and a 0 if it doesn't for each customer. There are only a small number of customers in this problem, so what I want back should look like this:
EquipmentID Cust1 Cust2 Cust3
----------- ----- ----- -----
1234 1 0 1
1357 0 1 0
2234 1 0 0
I can use a cross join to get a master list of possible records, but that returns the information in rows. I want to see it in columns, but the PIVOT keyword requires that I name the columns first. What I need is for the column names (Cust1, Cust2...) to be dynamic.

If you want to do that, then you have to create the query string dynamically and then pass it to the sp_execute stored procedure. AFAIK, there isn't a way to do it without constructing the query string dynamically.

If you have a reporting tool handy use your current query and make a "martix", "cross-tab", or "pivot table" report.

Related

Replacing the IN operator in Power BI RLS

I want to ask if its possible to use something like IN operator in Power BI RLS DAX.
The approach I am using now seems very convoluted to me, and I want to ask if it could be done better and simpler.
I have two types of identifiers in my Fact table: Code and GroupCode. Code is NOT NULL identifier and can have multiple unique GroupCodes and GroupCode can be NULL and can be assigned to multiple Code.
Example Fact table:
Code
GroupCode
Client
1
a
John
1
b
Susie
1
c
Mark
2
a
John
2
NULL
Mary
3
b
Susie
I want to create report where User enters by Code, but see all rows with it GroupCode.
In SQL it would be:
SELECT * FROM table
WHERE GroupCode IN (SELECT GroupCode FROM TABLE WHERE Code = '2') or Code = '2'
For now I created Dictionary table from my Fact table with Code and CodeDict, where CodeDict = ISNULL(GroupCode, Code). Also added CodeDict column to Fact table to create relation based on it, between Dict and Fact tables. Should be (1:*), but it shows (*:*).
Example Dict table:
Code
GroupCode
1
a
1
b
1
c
2
a
2
2
3
b
As for RLS rule it is set on Dict table as [Code] = #USERPRINCIPALNAME().
So for example if User open report using Code = 2. RLS will filter Dict table so CodeDict will be (a, 2) and by them, it will filter Fact table to shows rows with Code=(1, 2)
It's very convoluted approach and I don't like it, but I have no idea I could make it other way. I worry about (*:*) relation and that I have to create Bridge Dict table.
What do you think about this approach to this problem?
Is there a way to implement IN operator in RLS rule?

Access Append Query compare with table

I am currently rebuilding a messy Access Database and I entcountered the following problem:
I've got a Table of facilities which contain a row called district. Those Rows contain a number linked to another table which just contains the numbers and names of districts. I added a lookup Column with the Name of the district displayed.
I now want to change the new column for every row depending on the data in the old row.
Facilities
NAME|..|DISTRICT_OLD
A |..| 1
B |..| 2
C |..| 1
...
DISTRICTS
ID|NAME
1 |EAST
2 |WEST
...
I would like something like the following:
Facilities
NAME|..|DISTRICT_OLD|DISTRICT
A |..| 1|EAST
B |..| 2|WEST
C |..| 1|EAST
...
The District Field (lookup) gets its Data like follows SELECT [DISTRICTS].ID, [DISTRICTS].NAME FROM DISTRICTS ORDER BY [NAME];
(Thanks to Gordon Linoff) I could get the query but I do now struggle with the insert. I can get the Data I want:
SELECT [DISTRICTS].NAME FROM Facilities INNER JOIN DISTRICTS ON Facilities.DISTRICT_OLD = [DISTRICTS].ID;
If I try to INSERT INTO Facilities(DISTRICT) It says Typerror.
How can I modify the data to be compatible with a lookup column?
I guess I need to select the ID as well which isnt't a problem but then the error says to many columns.
I hope I haven't mistaken any names, my Access isn't running the english language.
Can you help me?
Fabian
Lookup columns are number (long integer)
with a relational database, you only need the single column containing the ID (as you always lookup the district.name with a query) so:
INSERT INTO Facilities(DISTRICT) SELECT 4
where 4 is the ID of the record in the lookup table that you want, or better still:
INSERT INTO Facilities(DISTRICT)
SELECT ID FROM DISTRICTS
where District.Name = "Name you want the ID for"

SQL If-Else logic based on value of one table

I have the following tables:
Production Table
SerialNumber WorkOrderNumber ItemName ItemType
1234 A2234 ASD 1
1234 A2234 ASD-T 2
1111 B2234 ZXC-T 2
WorkOrder Table
WorkOrderNumber ItemName ItemType
B2234 ZXC 1
B2234 ZXC-T 2
B2234 ZXC-C 3
Scenario: User inputs Serial Number, wants to get the item name of itemtype = 1 from either production table or workorder table
Desired Result
User input Serial number 1234 in application:
ItemName : ASD [Found in production table]
User input Serial number 1111 in application:
ItemName : ZXC [Found in workorder table]
Production and Workorder table is heavily simplified for demonstration purposes. The table contains millions of rows each. I need to come up with a performant query to get the item name.
The only solution I have thought of is to do the following
Use stored procedure and write an if-else logic
Check if the item type of the entered serial number is 1. If true, return itemname.
If itemtype is not 1, get the itemname from workorder table with itemtype = 1
But I'm not sure if that's a preferred method for performance and I feel kinda icky about putting business logic in database.
How would one handle this problem elegantly?
Try this:
select top 1 pt.serialNumber,pt.workOrderNumber,
isNull(wt.ItemName,pt.ItemName) as NameToReturn
from prodTable pt
left join worktable wt on pt.WorkOrderNumber=wt.workOrderNumber and wt.itemType=1
where pt.serialNumber = <input>
order by p1.itemType
Not sure I understand all your requirements, but the above should give you a start point. It finds the part in the prodTable and optionally finds a part in the work Item table. The is Null logic assumes that if a type one exists in Work table, it will be used. You might need to tweak this to a case statement if your rules are different (i.e. 1 in prod table should override worktable)

Join Two tables having different number of columns

I have a scenario like this in ssis - I have got two different inputs, out of which one is coming from a lookup nomatch output. The other input is actually a derived column that is takn from a single row single column result in an oledb source using sql query. The problem is that I need to join these two inputs and make it a single dataset to further push the data to the crm destination(Cozyroc).
I know union all just cant do the work since it works on union of rows from different datasets.
Also merge and merge join cannot be used since a common id or key need to be given inorder to join the two datasets, and i have got no such thing.
For example, my first dataset looks like:
usinessid userid name
--------- ------ ----
ret678 435 john
dfgt67 213 sam
and my second dataset is like:
systemid
------------------------
6666-777-kjtyr-213t-ytui
which is extracted using a single column single row query using the oledb source - sql command.
Is there a way to combine these two dataset so that the end result will be something like:
businessid userid name systemid
---------- ------ ---- ------------------------
ret678 435 john 6666-777-kjtyr-213t-ytui
dfgt67 213 sam 6666-777-kjtyr-213t-ytui
I want to do this without using a variable or using a derived column and hardcoding the systemid value.
Pardon my editing...
Any further inputs on this issue will be really helpful.
To combine the two datasets the way you've shown, you could use a simple cross join:
SELECT
t1.businessid,
t1.userid,
t1.name,
t2.systemid
FROM
table1 t1
CROSS JOIN
table2 t2
;

SQL Query -- IF X is shared between two strings in a primary composite key?

Not sure how to explain this, as I have only basic SQL knowledge. I need help with some logic to signal a user when a unique string is referenced more than once in a composite primary key.
A table I use contains a composite primary key which ties a unique "ItemCode" to a repeating "WarehouseCode". The "QuantityOnHand" column lists how much we have of an item in each warehouse:
_____PK_______
| |
ItemCode | WarehouseCode | QuantityOnHand
---------------------------------------------
001 A 100
001 B 500
002 A 600
003 B 250
etc.
How do I "signal" (create a boolean value?) when ItemCode 001 is in two separate warehouses?
The end result is a crystal report which somehow alerts the user when an item's total quantity is split between two warehouses.
Thanks
Utilise GROUP BY and HAVING. For example this query will return a list of ItemCodes and a count of how many warehouses they are in where that count is greater than 1.
SELECT ItemCode, COUNT(*)
FROM table
GROUP BY ItemCode
HAVING COUNT(*) > 1
In crystal you would probably want to create a group on ItemCode and then you can evaluate: DistinctCount({table.WarehouseCode}) but I would suggest you use SQL group by ItemCode having count(distinct WarehouseCode) > 1
It is much easier to do in Crystal than in pure SQL
Using a Crystal function:
If {table.ItemCode} = Previous({table.ItemCode})
Then //we have a duplicate ItemCode, do something to flag it
The above assumes that the details have these values and that they were not grouped. Although, even if they were grouped something like this should do it
If {table.ItemCode} = Previous({table.ItemCode})
and {table.WarehouseCode} <> Previous({table.WarehouseCode})
Then //we have a duplicate ItemCode