How to make rows into columns in SQL - sql

I have this table
SELECT PolicyID, ItemID, Period, Inventory1, Inventory2
FROM tblInventory
I want to convert this table into this:
The period will be converted as Column such as Inventory1 -1 and Inventory2 -1 until 4th period, per period there are two columns included: inventory1 and inventory2.
I would like to ask help on how to code this in SQL. Thank you!

To use PIVOT with your example you want to UNPIVOT the data first.
SELECT
*
FROM
(
SELECT
UP.PolicyId
, UP.ItemId
, CONCAT(UP.Inventories, '-', UP.Period) AS Inventories
, UP.Inventory
FROM
tblInventory AS TI
UNPIVOT
(
Inventory FOR Inventories IN (Inventory1, Inventory2)
) AS UP
) AS UNP
PIVOT
(
MAX(Inventory)
FOR Inventories IN
(
[Inventory1-1], [Inventory1-2], [Inventory1-3], [Inventory1-4]
, [Inventory2-1], [Inventory2-2], [Inventory2-3], [Inventory2-4]
)
) AS PVT

Related

Sequence row in SELECT Query

I have a simple SELECT statement in need sequence number according to result (no need to group or order by)I Used Row_Number but it need Over.
any other way to do it? Please help
SELECT
ROW_NUMBER() OVER () AS ArrayId (:here i need sequence number)
, TRIM(CM.Category) as Category
, TRIM(CM.SubCategory) as SubCategory
, CM.PlantCode
, ISNULL(PM.PlantName,'') as PlantName
, CM.Capacity AS Capacity_
, CM.SizeRange
, CM.CapacityId
FROM capacitymaster2 CM
LEFT JOIN PlantMaster2 PM ON CM.PlantCode = PM.PlantCode
WHERE CM.SubCategory IS NOT NULL AND CM.SubCategory != ''
Try: ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) if you need a unique sequence number, but don't care about the actual order.

MS-ACCESS / SQL - How to apply where clause in multiple conditions

SELECT Stock.*
FROM Stock
WHERE (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=2)
)
AND
(
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB")
)
OR (
(
(Stock.ComputerPartNumber) In (SELECT [ComputerPartNumber] FROM [Stock] As Tmp GROUP BY [ComputerPartNumber] HAVING Count(*)=1)
)
AND (
(Stock.EquipmentName)="EquipmentA" Or (Stock.EquipmentName)="EquipmentB"
)
);
I am using the above SQL to achieve below 3 items:-
Find out all of the ComputerPartNumber which used by EquipmentA and/or EquipmentB only
Filter out the query result if the ComputerPartNumber used by equipment other than EquipmentA and EquipmentB.
If the ComputerPartNumber is used by both EquipmentA and EquipmentC, filter out the result also.
However the item 3 cannot be filtered out successfully. What should I do in order to achieve the item3?
Table and Query snapshots are attached. Thanks in advance!
Table
Query
What you need to do is to check if the total number of times a part is used in all pieces of Equipment is equal to the total number of times a part is used by either Equipment A or B:
SELECT S.StorageID, S.ComputerPartNumber, S.EquipmentName, S.Result
FROM Stock AS S
WHERE
(SELECT COUNT(*) FROM Stock AS S1 WHERE S1.ComputerPartNumber=S.ComputerPartNumber)
=(SELECT COUNT(*) FROM Stock AS S2 WHERE S2.ComputerPartNumber=S.ComputerPartNumber AND S2.EquipmentName IN("EquipmentA","EquipmentB"))
Regards,
You can use not exists:
select s.*
from stock as s
where not exists (select 1
from stock as s2
where s2.ComputerPartNumber = s.ComputerPartNumber and
s2.EquipmentName not in ("EquipmentA", "EquipmentB")
);

Access Query subtract 2 different column from different row in same table with same ID

I have a table deposit which have column Refund_amt ,Deposit_amt having different Rows with same GR_no . here my question is ,I want to subtract deposit_amt column from Refund_amt
I tried various alternative in query but didn't succeed
My query :
SELECT d.Gr_no
, d.Rec_No
, d.Deposite_Amt
, d.penalty_Amt
, d.Refund_Amt - Refund
, s.Name
, s.cur_std
, cur_div
From
( select d.Refund_Amt refund
from deposite d
, std_gr s
where d.Gr_no = s.Gr_no )
Result would look like this in final total column :
Thank you
You are looking for an aggregation per std_gr: the sum of the deposites minus the sum of the refunds. One way is to do this aggregation in a subquery and join this subquery to your table.
select
d.*, sums.final_total
from deposite d
join
(
select std_gr, nz(sum(deposite_amt),0) - nz(sum(refund_amt),0) as final_total
from deposite
group by std_gr
) as sums on sums.std_gr = d.std_gr
order by d.rec_no;

unpivot calculated columns value

SELECT
P.EmployeeId,
(P.Amount*1)*T.RegularHours as RegularEarnings
,(P.Amount*1.5)*T.OTHours as OvertimeEarnings
,(P.Amount*2)*T.DOTHours as DoubleOvertimeEarnings
,((P.Amount*1)*T.RegularHours)+((P.Amount*1.5)*T.OTHours )+((P.Amount*2)*T.DOTHours)+((SELECT ISNULL(SUM(AMOUNT),0) FROM EmployeeEarning WHERE EmployeeId=T.EmployeeId)) as GrossPay
FROM TimeSheet as T
INNER JOIN PayInformation as P ON T.EmployeeId=P.EmployeeId
above is my select statement which returns me earnings in column format . I want to unpivot my resulted table so that each employeeId have two columns one is earning type and second one is amount of earning .
I already done with simple unpivote
select unpvt.car_id, unpvt.attribute, unpvt.value
from #cars c
unpivot (
value
for attribute in (Make, Model, Color)
) unpvt
but now stuck as i have to unpivot tables values calculated in select statement .
I have attempt something more and here is my latest code
SELECT unpvt.EmployeeId, unpvt.Earning, unpvt.Amount
FROM
(SELECT
P.EmployeeId,
(P.Amount*1)*T.RegularHours as RegularEarnings
,(P.Amount*1.5)*T.OTHours as OvertimeEarnings
,(P.Amount*2)*T.DOTHours as DoubleOvertimeEarnings
,((P.Amount*1)*T.RegularHours)+((P.Amount*1.5)*T.OTHours )+((P.Amount*2)*T.DOTHours)+((SELECT ISNULL(SUM(AMOUNT),0) FROM EmployeeEarning WHERE EmployeeId=T.EmployeeId)) as GrossPay
FROM TimeSheet as T
INNER JOIN PayInformation as P ON T.EmployeeId=P.EmployeeId )as c
unpivot (
Amount
for Earning in (RegularEarnings,OvertimeEarnings,DoubleOvertimeEarnings)
)unpvt
and now i am getting error
The type of column "OvertimeEarnings" conflicts with the type of other columns specified in the UNPIVOT list.

SQL query ...multiple max value selection. Help needed

Business World 1256987 monthly 10 2009-10-28
Business World 1256987 monthly 10 2009-09-23
Business World 1256987 monthly 10 2009-08-18
Linux 4 U 456734 monthly 25 2009-12-24
Linux 4 U 456734 monthly 25 2009-11-11
Linux 4 U 456734 monthly 25 2009-10-28
I get this result with the query:
SELECT DISTINCT ljm.journelname,ljm. subscription_id,
ljm.frequency,ljm.publisher, ljm.price, ljd.receipt_date
FROM lib_journals_master ljm,
lib_subscriptionhistory
lsh,lib_journal_details ljd
WHERE ljd.journal_id=ljm.id
ORDER BY ljm.publisher
What I need is the latest date in each journal?
I tried this query:
SELECT DISTINCT ljm.journelname, ljm.subscription_id,
ljm.frequency, ljm.publisher, ljm.price,ljd.receipt_date
FROM lib_journals_master ljm,
lib_subscriptionhistory lsh,
lib_journal_details ljd
WHERE ljd.journal_id=ljm.id
AND ljd.receipt_date = (
SELECT max(ljd.receipt_date)
from lib_journal_details ljd)
But it gives me the maximum from the entire column. My needed result will have two dates (maximum of each magazine), but this query gives me only one?
You could change the WHERE statement to look up the last date for each journal:
AND ljd.receipt_date = (
SELECT max(subljd.receipt_date)
from lib_journal_details subljd
where subljd.journelname = ljd.journelname)
Make sure to give the table in the subquery a different alias from the table in the main query.
You should use Group By if you need the Max from date.
Should look something like this:
SELECT
ljm.journelname
, ljm.subscription_id
, ljm.frequency
, ljm.publisher
, ljm.price
, **MAX(ljd.receipt_date)**
FROM
lib_journals_master ljm
, lib_subscriptionhistory lsh
, lib_journal_details ljd
WHERE
ljd.journal_id=ljm.id
GROUP BY
ljm.journelname
, ljm.subscription_id
, ljm.frequency
, ljm.publisher
, ljm.price
Something like this should work for you.
SELECT ljm.journelname
, ljm.subscription_id
, ljm.frequency
, ljm.publisher
, ljm.price
,md.max_receipt_date
FROM lib_journals_master ljm
, ( SELECT journal_id
, max(receipt_date) as max_receipt_date
FROM lib_journal_details
GROUP BY journal_id) md
WHERE ljm.id = md.journal_id
/
Note that I have removed the tables from the FROM clause which don't contribute anything to the query. You may need to replace them if yopu simplified your scenario for our benefit.
Separate this into two queries one will get journal name and latest date
declare table #table (journalName as varchar,saleDate as datetime)
insert into #table
select journalName,max(saleDate) from JournalTable group by journalName
select all fields you need from your table and join #table with them. join on journalName.
Sounds like top of group. You can use a CTE in SQL Server:
;WITH journeldata AS
(
SELECT
ljm.journelname
,ljm.subscription_id
,ljm.frequency
,ljm.publisher
,ljm.price
,ljd.receipt_date
,ROW_NUMBER() OVER (PARTITION BY ljm.journelname ORDER BY ljd.receipt_date DESC) AS RowNumber
FROM
lib_journals_master ljm
,lib_subscriptionhistory lsh
,lib_journal_details ljd
WHERE
ljd.journal_id=ljm.id
AND ljm.subscription_id = ljm.subscription_id
)
SELECT
journelname
,subscription_id
,frequency
,publisher
,price
,receipt_date
FROM journeldata
WHERE RowNumber = 1