I have this dataset:
DatasetMonthYear
Month Year Id Person_Id Name
-----------------------------------------------------
1 2007 855 5987456 John Slow
2 2007 850 5987456 John Slow
1 2007 254 5987456 John Slow
2 2008 987 5987456 John Slow
1 2007 456 5454543 Mary Jane
1 2007 454 5454543 Mary Jane
2 2008 554 5454543 Mary Jane
i need to group or count one row by month, Id and Person_Id, but counting that occurrence as one, so i make this query.
select pv.Person_Id, pv.Name, pv.Year,
(CASE [1] when 0 THEN 0 else 1 end) as January,
(CASE [2] when 0 THEN 0 else 1 end) as Februry
from DatasetMonthYear as P
pivot ( count(Id) for
Month in ([1], [2]) ) as pv
the result is this dataset:
Person_Id Name Year January February
------------------------------------------------------
5987456 John Snow 2007 1 0
5987456 John Snow 2007 0 1
5987456 John Snow 2008 0 1
5454543 Mary Jane 2007 1 0
5454543 Mary Jane 2008 0 1
now i need the sum of each month by one Person_Id on a year, so i try add another pivot as follows.
select Person_Id,Name, [2007], [2008]
from (select pv.Person_Id,pv.Name, Year, (CASE [1] when 0 THEN 0 else 1 end) as January,
(CASE [2] when 0 THEN 0 else 1 end) as February
from DatasetMonthYear as P
pivot ( count(Id) for
Month in ([1], [2]) ) as pv) as resulset
pivot( sum() for Year in ([2007],[2008]) ) as apv
and here is where i am stuck. i need a grouping by Person_ID, a sum of each month (January + Februry+...+etc) and pivot in years
Result i want :
2007 2008 Person_Id Name
2 1 5987456 John Snow
1 1 5454543 Mary Jane
I don't think you need two Pivots here, you can get your desired result using one Pivot, see below
select * from
(
select DISTINCT Person_Id, name, Year, Month From DatasetMonthYear
) Src
Pivot
(
Count(Month) For Year In ([2007],[2008])
) Pvt
SQL Demo
Related
I am trying to copy a piece of formatted text from one (rtf) document into a field in a Word document.
In Word2003, copy and paste via the clipboard works, but in Word2010, if the target range is in a footnote then the Paste operation fails (actually does nothing but does not give an error). In Word2010 however, using PasteSpecial works, but in Word365 that fails too.
This is my code:
If IsObjectValid(extIndex.getHeadingText(i)) Then
extIndex.getHeadingText(i).Copy
fieldCode.Collapse (wdCollapseEnd)
fieldCode.Paste
Else
Is there some other way to do this or am I doing something wrong?
I would like to filter emails in a subfolder.
Criterion: FlagRequest
Condition: "" '' Empty
I have the following attempts:
myRestrict = "[FlagRequest] = ''"
myRestrict = "[FlagRequest] ="""
myRestrict = "[FlagRequest] =' '"
myRestrict = "[FlagRequest] =''"
myRestrict = "[FlagRequest] =" & Chr (34) & Chr (34) & "
Dim allCount As Integer: allCount = 0
Dim restCounter As Integer: restCounter = 0
allCount = oFolder.Items.count
restCounter = oFolder.Items.Restrict (myRestrict) .count
Hits: 0
If I go to:
myRestrict = "[FlagRequest] <> '" & "Follow up" & "'"
I get the searched one, but also more.
When filtering an empty string with a DASL query, you can use the Is Null keyword. Is Null operations are useful to determine if a string property is empty or if a date property has been set. For more information, see Filtering Items Using Query Keywords.
myRestrict = "[FlagRequest] Is Null"
You can restrict to items where there is no entry with
myRestrict = "[FlagRequest] = """""
Hi I cant find anything regarding this, would be great if someone could point me in the right direction.
I have an access database with 4000 gym members.
I want to add profile pictures by linking from a given directory.
I dont want to manually link 4000 pictures
I want it to automatically search in the directory and match the firstname + last name + DOB of the member with the picture which will have the identical
eg: bobjones05121989
Thanks ahead for your help.
Are you using Access 2007 or later? Use the ControlSource property of Image control. An expression can construct the file path, like:
="C:\somepath\" & [FirstName] & [LastName] & Format([DOB], "ddmmyyyy") & ".jpg"
If image doesn't exist the Image control will be blank.
You can modify the function UrlContent to link from some other field(s) than ID, and not (as here) download anything (you have the files already) but just return the path of the picture:
' Download (picture) file from a URL of a hyperlink field to a
' (temporary) folder, and return the full path to the downloaded file.
'
' This can be used as the control source for a bound picture control.
' If no Folder is specified, the user's IE cache folder is used.
'
' Typical usage in the RecordSource for a form or report where Id is
' the unique ID and Url is the hyperlink field holding the URL to
' the picture file to be displayed:
'
' - to a cached file where parameter Id is not used:
'
' Select *, UrlContent(0, [Url]) As Path From SomeTable;
'
' - or, where Id is used to create the local file name:
'
' Select *, UrlContent([Id], [Url], "d:\somefolder") As Path From SomeTable;
'
' Then, set ControlSource of the bound picture control to: Path
'
' 2017-05-28. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function UrlContent( _
ByVal Id As Long, _
ByVal Url As String, _
Optional ByVal Folder As String) _
As Variant
Const NoError As Long = 0
Const Dot As String = "."
Const BackSlash As String = "\"
Dim Address As String
Dim Ext As String
Dim Path As String
Dim Result As String
' Strip leading and trailing octothorpes from URL string.
Address = HyperlinkPart(Url, acAddress)
' If Address is a zero-length string, Url was not wrapped in octothorpes.
If Address = "" Then
' Use Url as is.
Address = Url
End If
If Folder = "" Then
' Import to IE cache.
Result = DownloadCacheFile(Address)
Else
If Right(Folder, 1) <> BackSlash Then
' Append a backslash.
Folder = Folder & BackSlash
End If
' Retrieve extension of file name.
Ext = StrReverse(Split(StrReverse(Address), Dot)(0))
' Build full path for downloaded file.
Path = Folder & CStr(Id) & Dot & Ext
If DownloadFile(Address, Path) = NoError Then
Result = Path
End If
End If
UrlContent = Result
End Function
An article and a full demo can be found here:
Show pictures directly from URLs in Access forms and reports
Try this when the form loads.
You need to change the field names to the actual names of your database.
Private Sub Form_Load()
Dim imagepath As String
With Me
imagepath = "Drive:\" & LCase(![FirstName]) & LCase(![LastName]) & Format(![DOB], "ddmmyyyy") & ".jpg"
End With
If Len(Dir(imagepath)) > 0 Then
Me.ImageControl.Picture = imagepath
End If
End Sub
I am trying to create a Work Order System for a company and I am limited to using MS Access. I am wanting to code in a Work Order ID column. This column will be based on 2 combobox options:
BuildingName
TargetDepartment
I need some VBA code to query the WOID column in the table to retrieve the next number. The conditions will be as the below example:
WOID BuildingName TargetDepartment
BUILDA-DEPTA-1 BUILDA DEPTA
BUILDA-DEPTB-1 BUILDA DEPTB
BUILDA-DEPTA-2 BUILDA DEPTA
The VBA code would query the WOID column, and find out if there is a work order for the same building and department and then increment the number at the end by 1. But if there is no WOID that matches the buildingname and targetdepartment, it would create the first entry for that.
So if it finds a matching buildingname and targetdepartment: MaxNumber +1
If it doesn't find a matching buildingname and targetdepartment: 1
Thanks for the help!
You can do this using DLookUp :
where_condition = "[WOID] Like '" & Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-*'"
existing_woid = Nz(DLookUp("[WOID]","[TableName]", where_condition),"")
If(existing_woid = "") Then
next_id = 1
Else
next_id = DMax("Mid([WOID], InStrRev([WOID],""-"")+1)","[TableName]", where_condition) + 1
End If
woid = Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-" & next_id
You can do it in one line as well, but I think it is better to see the way of thinking behind this.
Edit (with record locking)
Dim s as String, rs as Recordset
s = " Select [WOID] From [TableName] " & _
" Where [WOID] Like '" & Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-*'" & _
" Order By 1 Desc"
'This will restrict table access
Set rs = CurrentDb.OpenRecordset(s, dbOpenDynaset, dbDenyRead + dbDenyWrite)
If rs.RecordCount > 0 Then
next_ind = Mid(rs(0), InStrRev(rs(0), "-") + 1) + 1
Else
next_ind = 1
End If
rs.AddNew
rs.Fields("WOID") = Me.[BuildingNameCombo] & "-" & Me.[TargetDepartmentCombo] & "-" & next_ind
rs.Update
rs.Close
Set rs = Nothing
I have a table X
ID A B C D
1 T T F T
2 F T F T
3 T F T F
So if my input is 1 for ID, then I want all column names that have value T for row 1. In above case A,B,D or If ID is 3 then A and C.
How could I list these columns?
You can use UNPIVOT for this
SELECT Y
FROM Table1
UNPIVOT (X FOR Y IN ([A], [B], [C], [D])) U
WHERE [ID] = 1 AND X = 'T'
Returns
+---+
| Y |
+---+
| A |
| B |
| D |
+---+
SQL Fiddle
Also you can use XQuery with powerful FLWOR Expression. And no matter how many columns contains a table;)
SELECT(
SELECT *
FROM Table1 t
WHERE ID = 1
FOR XML PATH(''), TYPE
).query(
'for $spec in ./*
where $spec [contains(., "T")]
return fn:local-name($spec)'
) o
Demo on SQLFiddle
This decision returns the names of columns on each row
SELECT o.TCols.value('.', 'nvarchar(100)') AS T
FROM(SELECT(
SELECT *
FROM Table1 t
WHERE ID = 1
FOR XML PATH(''), TYPE
).query('
for $spec in ./*
where $spec [contains(., "T")]
return (
<TCols>
{fn:local-name($spec)}
</TCols>
)
')) t(TCols) CROSS APPLY T.TCols.nodes('/TCols') o(TCols)
Results
+---+
| T |
+---+
| A |
| B |
| D |
+---+
Demo on SQLFiddle
In case that you know the number and name of all columns, you may do the below
SELECT case A when 'T' then 'A' else '' end
+ case B when 'T' then ',B' else '' end
+ case C when 'T' then ',C' else '' end
+ case D when 'T' then ',D' else '' end
FROM
Table1
WHERE ID = 1